Created
March 23, 2023 05:41
-
-
Save pablodz/c0f320f66f5394987240b3f4e036a32d to your computer and use it in GitHub Desktop.
gobs instead of json marshal golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Código con funciones abstraidas