This is a creation in Article, where the information may have evolved or changed.
This was a quick Friday blog post to talk about a recent experience I had working in a piece Juju code that needed to CAPTU Re the data being sent over a net.Conn .
Most Gophers know, the package net provides a net.Pipe function which returns a pair of net.Conn s representing an in Memor Y network connection. is ideal for testing-expect to talk over the net.Pipe network without all the mucking around of actually usin G The network.
The Go standard library also contains the Super useful io.MultiWriter function which takes any number of io.Writer s and returns another That would io.Writer send a copy of any data written to it underlying io.Writer s. Now I had all the pieces I needed to create a that net.Conn could record the data written through it.
Func Main () { client, server: = Net. Pipe () var buf bytes. Buffer client = io. Multiwriter (client, &BUF) //...}
Except This code does not compile.
# Command-line-arguments/tmp/sandbox866813815/main.go:13:cannot Use IO. Multiwriter (client, &BUF) (Type IO. Writer) as type net. Conn in Assignment:io. Writer does not implement net. Conn (missing Close method)
The value returned io.MultiWriter io.Writer by was an implementation of, it doesn ' t has the rest of the methods necessary to fulfil the net.Conninterface; What I really need are the ability to replace the Write method of a existing net.Conn value. We can do this with embedding by creating a structure the embeds both a and an net.Conn independant as io.Writer anonymous field S.
Type recordingconn struct { net. Conn io. Writer}func Main () { client, server: = Net. Pipe () var buf bytes. Buffer client = &recordingconn { conn:client, Writer:io. Multiwriter (client, &buf), } //...}
The recodingConn embeds a net.Conn ensuring that recordingConn implements net.Conn. It also gives us a place-to-hang the so io.MultiWriter we can syphon Off the data written by the client. There is only one small problem remaining.
# Command-line-arguments/tmp/sandbox439875759/main.go:24:recordingconn.write is ambiguous
Because both fields Write in the structure is types that has a method, the compiler cannot decide which one should be th E called. To resolve this ambiguity we can add a Write method on the recordingConn type itself:
Func (c *recordingconn) Write (buf []byte) (int, error) { return C.writer.write (BUF)}
With the ambiguity resolved, the was now recordingConn usable as a net.Conn implementation. You can see the full code here.
This is just a small example of the power of the struct composition using Go. Can think of other ways to does this?
Related Posts:
- The empty struct
- How to dial remote SSL/TLS services in Go
- Three new SSH client features in Go weekly.2011-11-18
- Accidental method Value