Created
September 28, 2017 20:37
-
-
Save 0x19/8ee072108d94a73a77abed9f2414fecf to your computer and use it in GitHub Desktop.
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 ( | |
"encoding/json" | |
"fmt" | |
"time" | |
redis "gopkg.in/redis.v6" | |
) | |
type Author struct { | |
FirstName string | |
LastName string | |
Email string | |
} | |
type Example struct { | |
Id int64 | |
Title string | |
Slug string | |
DateCreated time.Time | |
DateUpdated time.Time | |
Authors []Author | |
} | |
// MarshalBinary - | |
func (e *Example) MarshalBinary() ([]byte, error) { | |
return json.Marshal(e) | |
} | |
// UnmarshalBinary - | |
func (e *Example) UnmarshalBinary(data []byte) error { | |
if err := json.Unmarshal(data, &e); err != nil { | |
return err | |
} | |
return nil | |
} | |
func main() { | |
cache := redis.NewClient(&redis.Options{ | |
Addr: "", | |
Password: "", | |
DB: 0, | |
}) | |
if _, err := cache.Ping().Result(); err != nil { | |
fmt.Errorf("Could not ping redis server due to err: %s \n", err) | |
return | |
} | |
example := Example{ | |
Id: 12345, | |
Title: "Example Title", | |
Slug: "Example Slug", | |
DateCreated: time.Now().UTC(), | |
Authors: []Author{ | |
Author{ | |
FirstName: "Nevio", | |
LastName: "Vesic", | |
Email: "nevio.vesic@gmail.com", | |
}, | |
}, | |
} | |
cacheKey := "some.cache.key" | |
cacheField := "some-field-like-account-id" | |
if err := cache.HSet(cacheKey, cacheField, example).Err(); err != nil { | |
fmt.Printf("Unable to store example struct into redis due to: %s \n", err) | |
return | |
} | |
cacheData, cacheErr := cache.HGet(cacheKey, cacheField).Result() | |
if cacheErr != nil { | |
fmt.Printf("Unable to retrieve example struct from redis due to: %s \n", cacheErr) | |
return | |
} | |
var newExample Example | |
if err := newExample.UnmarshalBinary([]byte(cacheData)); err != nil { | |
fmt.Printf("Unable to unmarshal data into the new example struct due to: %s \n", err) | |
return | |
} | |
fmt.Printf("Example.UnmarshalBinary: %+v \n", newExample) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment