Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GO: How to save and retrieve a struct to redis using redigo

Tags:

go

i am using GO and trying to save and retrieve array of struct's in redis. How can i go about implementing it.

i have the following struct

type Resource struct {
   title string
}

and am saving the resources using the following code

_, err := redigo.Do("lpush", <unique id>, <resource object>);

now how can i retrieve the array of structure objects from redis.

like image 657
Sathya Avatar asked Dec 14 '14 10:12

Sathya


1 Answers

Since you're going to marsal code back and forth, I'd suggest going with @Not_a_Golfer's solution.

Here is a sample of what you can do:

package main

import (
    "encoding/json"
    "fmt"
)

type Emotions struct {
    Sad      bool
    Happy    Happy
    Confused int
}

type Happy struct {
    Money  int
    Moral  bool
    Health bool
}

func main() {

    emo := &Emotions{Sad: true}

    // retain readability with json
    serialized, err := json.Marshal(emo)

    if err == nil {
        fmt.Println("serialized data: ", string(serialized))
//serialized data:  {"Sad":true,"Happy":{"Money":0,"Moral":false,"Health":false},"Confused":0}
        //do redis transactions...
    }

    //retriving whatever value stored in your redis instance...

    var deserialized Emotions

    err = json.Unmarshal(serialized, &deserialized)

    if err == nil {
        fmt.Println("deserialized data: ", deserialized.Sad)
//deserialized data:  true
    }
}

Now regarding how you should store things on redis, it depends pretty much on your data.

like image 106
ymg Avatar answered Nov 09 '22 05:11

ymg