Golang: Serialize struct using gob: Part 1

Serialize of the struct will help you to transfer data over network or it will help you to write data on disk. In a distributed system you...

Share on:  
                 

alt

Golang: Serialize struct using gob: Part 1

Serialize of the struct will help you to transfer data over network or it will help you to write data on disk. In a distributed system you generate data then serialize, compress and send. On other end you receive data then decompress, deserialize and process. The entire process must be fast and efficient. Go lang has it’s own serialize format called gob. Using gob you can encode and decode structure. You can use other formats like JSON, XML, protobuff, capnproto, etc.. You should choose a format or protocol based on your requirement. I suggest to use Go’s gob format when you have sender and receiver both are developed in Go lang.

Package: pkg/encoding/gob

  1. Stream of gob is self describing, It means we don’t need to create separate file to explain, like we need to create file in protobuff
  2. Each data item in the stream is preceded by a specification of its type, expressed in terms of a small set of predefined types.

Gob is very simple package from out side. It has only 8 functions and 5 types.

func Register(value interface{})\
func RegisterName(name string, value interface{})\
type CommonType\
type Decoder\
 func NewDecoder(r io.Reader) \*Decoder\
 func (dec \*Decoder) Decode(e interface{}) error\
 func (dec \*Decoder) DecodeValue(v reflect.Value) error\
type Encoder\
 func NewEncoder(w io.Writer) \*Encoder\
 func (enc \*Encoder) Encode(e interface{}) error\
 func (enc \*Encoder) EncodeValue(value reflect.Value) error\
type GobDecoder\
type GobEncoder

Example 1

In this simple example, We have student structure. It has two fields Name and Age. We have used method gob.NewEncoder and gob.NewDecoder both methods accepts io.Writer and io.Reader object. These methods use to write and read gob file.

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

type Student struct {
       Name string
       Age int32
}

func main() {

       fmt.Println("Gob Example")
       student := Student{"Ketan Parmar",35}
       err := writeGob("./student.gob",student)
       if err != nil{
              fmt.Println(err)
       }


       var studentRead = new (Student)
       err = readGob("./student.gob",studentRead)
       if err != nil {
              fmt.Println(err)
       } else {
              fmt.Println(studentRead.Name, "\t", studentRead.Age)
       }


}

func writeGob(filePath string,object interface{}) error {
       file, err := os.Create(filePath)
       if err == nil {
              encoder := gob.NewEncoder(file)
              encoder.Encode(object)
       }
       file.Close()
       return err
}

func readGob(filePath string,object interface{}) error {
       file, err := os.Open(filePath)
       if err == nil {
              decoder := gob.NewDecoder(file)
              err = decoder.Decode(object)
       }
       file.Close()
       return err
}

Example 2

Let’s create array / slice of student structure and fill some data. For following example we do not need to change readGob and writeGob functions.

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

type Student struct {
       Name string
       Age int32
}
type Students []Student

func main() {

       fmt.Println("Gob Example")
       students := Students{}
       students = append(students,Student{"Student 1",20})
       students = append(students,Student{"Student 2",25})
       students = append(students,Student{"Student 3",30})


       err := writeGob("./student.gob",students)
       if err != nil{
              fmt.Println(err)
       }

       var studentRead = new (Students)
       err = readGob("./student.gob",studentRead)
       if err != nil {
              fmt.Println(err)
       } else {
              for _,v := range *studentRead{
                     fmt.Println(v.Name, "\t", v.Age)
              }
       }
}

In this article, I have explored NewEncoder and NewDecoder functions. In next article, I will explore other functions like Register, Encode, EncodeValue, Decode and DecodeValue.

Reference

  1. https://blog.golang.org/gobs-of-data
  2. https://golang.org/pkg/encoding/gob/
  3. http://www.robotamer.com/code/go/gotamer/gob.html
  4. https://github.com/alecthomas/go_serialization_benchmarks
  5. https://appliedgo.net/networking
Tags:   GOGO LANGSERIALIZE