In this Getting Started with Golang, we will learn how to use the Golang Gob Encoding. Package gob manages streams of gobs - binary values exchanged between an Encoder (transmitter) and a Decoder (receiver). A typical use is transporting arguments and results of remote procedure calls (RPCs) such as those provided by package "net/rpc" with step by step guide in Golang programming language.
#MaharlikansCode
#GobEncoding
#Golang
#LifeAsSoftwareDeveloper
#Maharlikans
#FilipinoSoftwareDeveloper
If you go with extra mile for buying me a cup of coffee, I appreciate it guys: https://ko-fi.com/maharlikanscode
Source Codes:
package main
import (
"bytes"
"encoding/gob"
"errors"
"fmt"
"strings"
"sync"
)
// Person is the collections of personal information
type Person struct {
UserName, FirstName, LastName string
Age int
UserEmail Email
}
// PersonData is the main storage of all the personal information to the memory
type PersonData struct {
UserName map[string][]byte
mu sync.Mutex
}
// Email is the collection of user's email information
type Email struct {
Name, Address string
}
// ST map collection type structure...
type ST map[string]interface{}
// PD initialize the 'PersonData' struct with an empty values
var PD = PersonData{UserName: make(map[string][]byte)}
// Add is to insert new row to the map collection called 'PersonData'
func (p *PersonData) Add(userName string, encBytes []byte) {
if len(strings.TrimSpace(userName)) greater than 0 {
p.mu.Lock()
defer p.mu.Unlock()
p.UserName[userName] = encBytes
}
}
// Get gets the specific username as the key to return the value
func (p *PersonData) Get(userName string) ([]byte, bool) {
personData, ok := p.UserName[userName]
if !ok {
return personData, ok
}
return personData, ok
}
// Remove any specific key using the username
func (p *PersonData) Remove(userName string) bool {
p.mu.Lock()
defer p.mu.Unlock()
_, ok := p.UserName[userName]
if !ok {
return false
}
delete(p.UserName, userName)
return true
}
// EncodePayload encodes the Person's struct collection
func EncodePayload(payLoad Person) ([]byte, error) {
var data bytes.Buffer
enc := gob.NewEncoder(&data)
err := enc.Encode(payLoad)
if err != nil {
return data.Bytes(), err
}
return data.Bytes(), nil
}
// DecodePayload extracts the data from the 'Person' structs
func DecodePayload(userName string) (Person, error) {
if len(strings.TrimSpace(userName)) == 0 {
return Person{}, errors.New("username key is required")
}
var payLoad = Person{}
payLoadBytes, _ := PD.Get(userName)
dec := gob.NewDecoder(bytes.NewReader(payLoadBytes))
err := dec.Decode(&payLoad)
if err != nil {
return Person{}, errors.New("username key is not found: " + userName)
}
return payLoad, nil
}
func main() {
isAdded, err := newPerson("aaa", "John", "Rambo", 56, Email{"John Rambo", "[email protected]"})
if err != nil {
fmt.Println("Oops!, got some errors: ", err)
}
if isAdded {
fmt.Println("New person has been added successfully!")
}
// Decode the payload
d, err := DecodePayload("aaa")
if err != nil {
fmt.Println("Decoding of payload error: ", err)
}
// Display the specified extracted personal information
fmt.Println("First Name: ", d.FirstName)
// Remove the existing key
fmt.Println("Removing username: aaa")
PD.Remove("aaa")
// Decode the payload
d, err = DecodePayload("aaa")
if err != nil {
fmt.Println("Decoding of payload error: ", err)
}
// Display the specified extracted personal information
fmt.Println("First Name: ", d.FirstName)
}
func newPerson(userName, firstName, lastName string, age int, userEmail Email) (bool, error) {
if len(strings.TrimSpace(userName)) == 0 {
return false, errors.New("username is required")
}
if len(strings.TrimSpace(firstName)) == 0 {
return false, errors.New("first name is required")
}
if len(strings.TrimSpace(lastName)) == 0 {
return false, errors.New("last name is required")
}
newPersonData := Person{
UserName: strings.TrimSpace(userName),
FirstName: strings.TrimSpace(firstName),
LastName: strings.TrimSpace(lastName),
Age: age,
UserEmail: userEmail,
}
encBytes, err := EncodePayload(newPersonData)
if err != nil {
return false, err
}
PD.Add(userName, encBytes)
return true, nil
}