Skip to content

Instantly share code, notes, and snippets.

@pablodz
Created March 23, 2023 05:41
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save pablodz/c0f320f66f5394987240b3f4e036a32d to your computer and use it in GitHub Desktop.
gobs instead of json marshal golang
package main
import (
"bytes"
"encoding/gob"
"fmt"
"github.com/go-redis/redis"
)
type Address struct {
Street string
City string
State string
Zip string
}
type User struct {
ID int
Name string
Age int
Address *Address
}
func main() {
// Connect to Redis
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0, // use default DB
})
// Initialize the encoder and decoder
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
dec := gob.NewDecoder(&buf)
// Create an instance of the struct to be stored
address := &Address{Street: "123 Main St", City: "Anytown", State: "CA", Zip: "12345"}
user := User{ID: 123, Name: "John Doe", Age: 30, Address: address}
// Encode the struct and store it in Redis
err := enc.Encode(user)
if err != nil {
panic(err)
}
err = client.Set("user123", buf.Bytes(), 0).Err()
if err != nil {
panic(err)
}
// Retrieve the serialized struct from Redis and decode it
val, err := client.Get("user123").Bytes()
if err != nil {
panic(err)
}
buf.Reset()
buf.Write(val)
var user2 User
err = dec.Decode(&user2)
if err != nil {
panic(err)
}
// Print the decoded struct to verify it was retrieved correctly
fmt.Println(user2) // output: {123 John Doe 30 &{123 Main St Anytown CA 12345}}
}
@pablodz
Copy link
Author

pablodz commented Mar 23, 2023

Código con funciones abstraidas

package main

import (
	"bytes"
	"context"
	"encoding/gob"
	"fmt"
	"log"

	"github.com/go-redis/redis/v8"
)

type Address struct {
	Street string
	City   string
	State  string
	Zip    string
}

type User struct {
	ID      int
	Name    string
	Age     int
	Address *Address
}

func Encode(v interface{}) ([]byte, error) {
	var buf bytes.Buffer
	enc := gob.NewEncoder(&buf)
	err := enc.Encode(v)
	if err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}

func Decode(data []byte, v interface{}) error {
	buf := bytes.NewBuffer(data)
	dec := gob.NewDecoder(buf)
	return dec.Decode(v)
}

func main() {
	// Connect to Redis
	ctx := context.Background()
	client := redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "", // no password set
		DB:       0,  // use default DB
	})

	// Close the client when the function returns
	defer func() {
		if err := client.Close(); err != nil {
			log.Fatalf("failed to close Redis client: %v", err)
		}
	}()

	// Create an instance of the struct to be stored
	address := &Address{Street: "123 Main St", City: "Anytown", State: "CA", Zip: "12345"}
	user := User{ID: 123, Name: "John Doe", Age: 30, Address: address}

	// Encode the struct and store it in Redis
	data, err := Encode(user)
	if err != nil {
		log.Fatalf("failed to encode user: %v", err)
	}
	err = client.Set(ctx, "user123", data, 0).Err()
	if err != nil {
		log.Fatalf("failed to store user in Redis: %v", err)
	}

	// Retrieve the serialized struct from Redis and decode it
	data, err = client.Get(ctx, "user123").Bytes()
	if err != nil {
		log.Fatalf("failed to retrieve user from Redis: %v", err)
	}
	var user2 User
	err = Decode(data, &user2)
	if err != nil {
		log.Fatalf("failed to decode user: %v", err)
	}

	// Print the decoded struct to verify it was retrieved correctly
	fmt.Println(user2) // output: {123 John Doe 30 &{123 Main St Anytown CA 12345}}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment