Golang: Serialize struct using gob: Part 2

In this article we will explore following functions of gob

Share on:  
                 

alt

[Golang: Serialize struct using gob — Part 2

In this article we will explore following functions of gob

func (dec \*Decoder) Decode(e interface{}) error

func (enc \*Encoder) Encode(e interface{}) error

Encode and Decode functions are helpful when you want to write network application.

Example 1:

Simple encoding and decoding student structure

package main
import (
   "fmt"
   "encoding/gob"
   "bytes"
)

type Student struct {
   Name string
   Age int32
}

func main() {

   fmt.Println("Gob Example")

   studentEncode := Student{Name:"Ketan",Age:30}
   
   var b bytes.Buffer
   e := gob.NewEncoder(&b)
   if err := e.Encode(studentEncode); err != nil {
      panic(err)
   }
   fmt.Println("Encoded Struct ", b)

   var studentDecode Student
   d := gob.NewDecoder(&b)
   if err := d.Decode(&studentDecode); err != nil {
      panic(err)
   }

   fmt.Println("Decoded Struct ", studentDecode.Name,"\t",studentDecode.Age)


}

It’s is a simple example. In which we serialize and deserialize Student Struct. After encoding Student struct, It stores in byte buffer “b” now, we can use variable “b” to transfer over the network. To Decode byte buffer, we just need to create the object of the same structure and provide the address of a variable. In above example we have “studentEncode” variable which we have used for encoding and studentDecode variable is used for decoding.

Example 2:

Encoding student structure and pass over TCP connection.

TCP Client: It dial open TCP connection and transfer student object using gob.Encoder method.

package main
import (
   "fmt"
   "encoding/gob"
   "net"
   "log"
)
type Student struct {
   Name string
   Age int32
}
func main() {
   fmt.Println("Client")
   //create structure object
    studentEncode := Student{Name:"Ketan",Age:30}

   fmt.Println("start client");
   // dial TCP connection
   conn, err := net.Dial("tcp", "localhost:8080")
   if err != nil {
      log.Fatal("Connection error", err)
   }
   //Create encoder object, We are passing connection object in Encoder
   encoder := gob.NewEncoder(conn)
   // Encode Structure, IT will pass student object over TCP connection
   encoder.Encode(studentEncode)
   // close connection
   conn.Close()
   fmt.Println("done");
}

TCP Server: It listen on port 8080, Handle all client connection in go routine. Decode Student structure using gob.Decoder and print.

package main

import (
   "fmt"
   "net"
   "encoding/gob"
)

type Student struct {
   Name string
   Age int32
}

func handleConnection(conn net.Conn) {
   // create new decoder object and provide connection
   dec := gob.NewDecoder(conn)
   // create blank student object
   p := &Student{}
   // decode serialize data
   dec.Decode(p)
   // print
   fmt.Println("Hello ",p.Name,", Your Age is ",p.Age);
   // close connection for that client
   conn.Close()
}

func main() {
   fmt.Println("Server")
   // start TCP server and listen on port 8080
   ln, err := net.Listen("tcp", ":8080")
   if err != nil {
      // handle error
      panic(err)
   }
   for {
      // this blocks until connection or error
      conn, err := ln.Accept()
      if err != nil {
         // handle error
         continue
      }
      // a goroutine handles conn so that the loop can accept other connections
      go handleConnection(conn)
   }
}

Questions:

  1. What if you have different fields for Client and Server?
  2. What if you have same fields but different sequence?
  3. What if you have different data type for the fields?

Answer:

  1. Find your self :-)

Reference

  1. https://blog.golang.org/gobs-of-data
  2. https://golang.org/pkg/encoding/gob/
Tags:   GOGO LANGSERIALIZE