Sending your Structs across the wire (tcp connection)

Sending your structs across the wire and receiving them on the other side. Using encoding/gob can help ensure your data structures can receive it on the other side.

// server.go

package main

import ...

// Create your custom data struct
type Message struct {
  ID   string
  Data string
}

func main() {
  // for purpose of verbosity, I will be removing error handling from this
  // sample code

  server, err  := net.Listen("tcp", ":12345")
  conn, err = server.Accept()

  // create a temp buffer
  tmp := make([]byte, 500)

  // loop through the connection to read incoming connections. If you're doing by
  // directional, you might want to make this into a seperate go routine
  for {

    _, err = conn.Read(tmp)
    
    // convert bytes into Buffer (which implements io.Reader/io.Writer)
    tmpbuff := bytes.NewBuffer(tmp)

    tmpstruct := new(Message)

    // creates a decoder object
    gobobj := gob.NewDecoder(tmpbuffer)

    // decodes buffer and unmarshals it into a Message struct
    gobobj.decode(tmpstruct)

    // lets print out!
    fmt.Println(tmpstruct) // reflects.TypeOf(tmpstruct) == Message{}

  }

}
// client.go

import ...

type Message struct {
  ID   string
  Data string
}

func main(){
  // lets create the message we want to send accross
  msg := Message{ID: "Yo", Data: "Hello"}
  bin_buf := new(bytes.Buffer)

  // error handling still truncated
  conn, err

  // create a encoder object
  gobobj := gob.NewEncoder(bin_buf)

  // encode buffer and marshal it into a gob object
  gobobj.Encode(msg)

  conn.Write(bin_buf.Bytes())
}

References