Search code examples
goweb-applicationsredisproject-structureredigo

Is there any auto incremention machanim for storing keys' values in redis with redigo wrapper?


I'm new to go programming language and just wanted to write a small web app project with a good architecture.

I get some specific recangle objects through a post request.

type Rectangle struct {
X         int //starting x coordinate
Y         int //starting y coordinate
Width     int
Height    int
CreatedAt time.Time
}

I decided to choose redis for storing because it has high performance and I wanted to get my hands on that.

I have a bit confusion here :

  1. There is no specific key in the object's nature for storing, so I came up with the idea of auto incremention of keys but still stuck how to that because as I studied the pattern for insertion, it's something like:

    json, err := json.Marshal(rectangle)
    if err != nil {
        return err
    }
    
    _, err = connection.Do("SET", key, json)
    if err != nil {
        return err
    }
    

As you can see, I'm stuck what to write in the key field. I saw the Redis commands "INCR" but it seems none make sense for this pattern.

  1. If I want to get all rectangles regardless of their keys, will connection.Do("HGETALL", "*", rectangles[]) command help me get an array of all rectangles in the databse?

Solution

  • A list meets the requirements set forth in the question.

    Add rectangle:

     _, err := c.Do("RPUSH", "rectangles", rectJSON). 
    

    Get all rectangles:

    rectJSONs, err := redis.ByteSlices(c.Do("LRANGE" "rectangles", 0, -1))
    if err != nil {
       // handle error
    }
    var rectangles []*Rectangle
    for _, rj := range rectJSONS {
       var r Rectangle
       if err := json.Unmarshal(rj, &r); err != nil {
           // handle error
       }
       rectangles = append(rectangles, &r)
    }