↓ Skip to main content
Go

GoLang: encoding

Table of Contents

Package encoding provide capabilities to convert data to and from byte-level and textual representations.

  • encoding/gob
  • encoding/json, and
  • encoding/xml
The gob is Go’s format for serializing and deserializing. The gob was tailored for communicating between two servers written in Go.
  • Only exported fields are encoded; zero values are not taken into account
Package gob manages streams of gobs – binary values exchanged between an Encoder (transmitter) and a Decoder (receiver).

Format GoB
#

Let’s create a simple Type Blog and we will encode and decode it using the gob format.

package enc

import (
	"encoding/gob"
	"flag"
	"fmt"
	"log"
	"os"
)

// Blog blog structure
type Blog struct {
	Title, Author, Category string
	Length                  int
}

func (b *Blog) String() string {
	return fmt.Sprintf(" Blog: %s @ %s\n Category: %s\n Length: %d", b.Title, b.Author, b.Category, b.Length)
}

var fileName string
var logger = log.New(os.Stdout, " ENC: ", log.LUTC)

func init() {
	flag.StringVar(&fileName, "f", "", "Output/Input file")
	flag.Parse()
}

const (
	//ErrorMessage For the errors
	ErrorMessage = "need a file to write or read the contents."
)

var defBlog = Blog{Title: "My first blog", Author: "Samarthya", Category: "technical", Length: 200}

// Cmd main entry method
func Cmd() {
	if flag.NFlag() == 0 {
		flag.PrintDefaults()
		logger.Fatalf("%s", ErrorMessage)
	}

	f, err := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, 0666)

	defer f.Close()

	if err != nil {
		logger.Fatalf("%s", err.Error())
		os.Exit(1)
	}

	enc := gob.NewEncoder(f)
	err = enc.Encode(&defBlog)
	if err != nil {
		logger.Fatalf("%s", err.Error())
		os.Exit(1)
	}

	dec := gob.NewDecoder(f)
	var blogR Blog

	f.Seek(0,0)
	err = dec.Decode(&blogR)
	if err != nil {
		logger.Fatalf("%s", err.Error())
		os.Exit(1)
	}

	fmt.Printf(" Read: %s\n", blogR.String())
	fmt.Println(" --- End Program -- ")
}
./main -f abc.txt
 Read:  Blog: My first blog @ Samarthya
 Category: technical
 Length: 200
 --- End Program --
Author
Samarthya
Engineer, learner, tinkerer. This is my trophy shelf of everyday work and leisure.

Related

GoLang: Hex Output

·3 mins
In last few blogs I have written about reading commandline parameters reading files and using the os package. In this blog, I will combine some these items to read a file byte by byte using the bufio package func’s.

GoLang: Program Banner

·2 mins
In the last blog I talked about command line arguments os.Args[]. In this I will try and create a sample banner program that shall Take 3 arguments n - Number of times a message has to be repeated. m - The message that needs to be shown. d - If debug message needs to be shown. I am going to use the flags package.

GoLang: Command line arguments

·1 min
Reading the golang official documentation is fun, today I saw the Variables in package os var Args []string It allows you to hold command line arguments and a simple main program that can help you validate this.