本文整理匯總了Golang中github.com/garyburd/redigo/redis.ScanStruct函數的典型用法代碼示例。如果您正苦於以下問題:Golang ScanStruct函數的具體用法?Golang ScanStruct怎麽用?Golang ScanStruct使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了ScanStruct函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: Value
func (iter *subscriptionIterator) Value() *subscriptionInfo {
sub := &subscriptionInfo{}
reply, _ := redis.Values(iter.conn.Do("HGETALL", iter.values[0]))
redis.ScanStruct(reply, sub)
return sub
}
示例2: GetTokenValue
func (strg *Storage) GetTokenValue(key string, t interface{}) error {
var (
data []interface{}
err error
)
if item := db.Cache.Get(key); item != nil && item.Value() != nil {
if !item.Expired() {
data = item.Value().([]interface{})
}
}
if len(data) == 0 {
data, err = db.GetHCache(key)
if err != nil {
return err
}
}
if err = redis.ScanStruct(data, t); err != nil {
fmt.Print(err)
return err
}
if len(data) > 0 {
db.Cache.Replace(key, data)
}
return nil
}
示例3: TestSendReceiveWithWait
func TestSendReceiveWithWait(t *testing.T) {
conn := NewConn()
conn.ReceiveWait = true
conn.Command("HGETALL", "person:1").ExpectMap(map[string]string{
"name": "Mr. Johson",
"age": "42",
})
conn.Command("HGETALL", "person:2").ExpectMap(map[string]string{
"name": "Ms. Jennifer",
"age": "28",
})
ids := []string{"1", "2"}
for _, id := range ids {
conn.Send("HGETALL", fmt.Sprintf("person:%s", id))
}
var people []Person
var peopleLock sync.RWMutex
go func() {
for i := 0; i < len(ids); i++ {
values, err := redis.Values(conn.Receive())
if err != nil {
t.Fatal(err)
}
var person Person
err = redis.ScanStruct(values, &person)
if err != nil {
t.Fatal(err)
}
peopleLock.Lock()
people = append(people, person)
peopleLock.Unlock()
}
}()
for i := 0; i < len(ids); i++ {
conn.ReceiveNow <- true
}
time.Sleep(10 * time.Millisecond)
peopleLock.RLock()
defer peopleLock.RUnlock()
if len(people) != 2 {
t.Fatalf("Wrong number of people. Expected '2' and got '%d'", len(people))
}
if people[0].Name != "Mr. Johson" || people[1].Name != "Ms. Jennifer" {
t.Error("People name order are wrong")
}
if people[0].Age != 42 || people[1].Age != 28 {
t.Error("People age order are wrong")
}
}
示例4: getComments
func getComments(conn redis.Conn, host, path string) ([]comment, error) {
ids, err := redis.Strings(conn.Do("ZRANGEBYSCORE",
fmt.Sprintf(keyApproved, host, path),
"-inf", "+inf", "LIMIT", "0", "10"))
if err != nil {
return nil, err
}
comments := make([]comment, 0) // empty list, instead of nil
for _, id := range ids {
intid, _ := strconv.ParseInt(id, 10, 64)
vals, err := redis.Values(conn.Do("HGETALL",
fmt.Sprintf(keyComment, host, path, intid)))
if err != nil {
return nil, err
}
var c comment
if err = redis.ScanStruct(vals, &c); err != nil {
return nil, err
}
c.ID = id
c.Author = c.Author
c.Content = c.Content
comments = append(comments, c)
}
return comments, nil
}
示例5: ReadAllTasks
// ReadAllTasks load all unfinished task
func ReadAllTasks() []Task {
c := Pool.Get()
defer c.Close()
var GetAllTasksLua = `
local data = redis.call("LRANGE", "allTasks", "0", "-1")
local ret = {}
for idx=1, #data do
ret[idx] = redis.call("HGETALL", "task:"..data[idx])
end
return ret
`
var tasks []Task
script := redis.NewScript(0, GetAllTasksLua)
values, err := redis.Values(script.Do(c))
if err != nil {
log.Println(err)
}
for i := range values {
t := new(Task)
redis.ScanStruct(values[i].([]interface{}), t)
tasks = append(tasks, *t)
}
return tasks
}
示例6: Subscribe
func (chat *Chat) Subscribe() {
psc := redis.PubSubConn{pool.Get()}
psc.Subscribe("chat")
c := pool.Get()
for {
switch v := psc.Receive().(type) {
case redis.Message:
log.Printf("%s: message %s\n", v.Channel, v.Data)
id, err := redis.Int(v.Data, nil)
if err != nil {
log.Println(err)
return
}
result, err := redis.Values(c.Do("HGETALL", "message:"+strconv.Itoa(id)))
if err != nil {
log.Println(err)
return
}
var message Message
err = redis.ScanStruct(result, &message)
if err != nil {
log.Println(err)
return
}
chat.outgoing <- &message
case redis.Subscription:
log.Printf("%s: %s %d\n", v.Channel, v.Kind, v.Count)
case error:
log.Println(v)
return
}
}
}
示例7: get_source_by_id
func get_source_by_id(res rest.ResponseWriter, conn redis.Conn, contentType string, doc_id string) (map[string]interface{}, bool) {
hash_key := "index:" + contentType + ":source:" + doc_id
hash_value := Source{"", "", "", 0}
exists, err := redis.Bool(conn.Do("EXISTS", hash_key))
if err != nil {
rest.Error(res, "Unexpected error. "+err.Error(), 400)
return nil, true
}
if exists == false {
return nil, false
}
// get the document indexed
values, err := conn.Do("HGETALL", hash_key)
if err == nil {
err = redis.ScanStruct(values.([]interface{}), &hash_value)
}
if err != nil {
rest.Error(res, "Unexpected error. "+err.Error(), 400)
return nil, true
}
source := structs.Map(hash_value)
source["Id"] = doc_id
source["Payload"] = StringToJson(source["Payload"].(string))
return source, false
}
示例8: getProcedure
func getProcedure(pool *redis.Pool, endpoint URI) *registrationInfo {
conn := pool.Get()
defer conn.Close()
proceduresKey := fmt.Sprintf("procedures:%s", endpoint)
procedures, err := redis.Strings(conn.Do("ZREVRANGE", proceduresKey, 0, 1))
if err != nil {
out.Debug("Redis error on key %s: %v", proceduresKey, err)
return nil
}
if len(procedures) == 0 {
return nil
}
info := registrationInfo{}
reply, err := redis.Values(conn.Do("HGETALL", procedures[0]))
if err != nil {
out.Debug("Redis error on key %s: %v", procedures[0], err)
return nil
}
err = redis.ScanStruct(reply, &info)
if err != nil {
out.Debug("Redis error on key %s: %v", procedures[0], err)
return nil
}
return &info
}
示例9: CmdShow
func (c *cli) CmdShow(args ...string) error {
cmd := SubCmd("show", "[IDENTIFIER]", "Print a mirror configuration")
if err := cmd.Parse(args); err != nil {
return nil
}
if cmd.NArg() != 1 {
cmd.Usage()
return nil
}
// Guess which mirror to use
list, err := c.matchMirror(cmd.Arg(0))
if err != nil {
return err
}
if len(list) == 0 {
fmt.Fprintf(os.Stderr, "No match for %s\n", cmd.Arg(0))
return nil
} else if len(list) > 1 {
for _, e := range list {
fmt.Fprintf(os.Stderr, "%s\n", e)
}
return nil
}
id := list[0]
// Connect to the database
r := NewRedis()
conn, err := r.connect()
if err != nil {
log.Fatal("Redis: ", err)
}
defer conn.Close()
// Get the mirror information
key := fmt.Sprintf("MIRROR_%s", id)
m, err := redis.Values(conn.Do("HGETALL", key))
if err != nil {
fmt.Fprintf(os.Stderr, "Cannot fetch mirror details: %s\n", err)
return err
}
var mirror Mirror
err = redis.ScanStruct(m, &mirror)
if err != nil {
return err
}
// Generate a yaml configuration string from the struct
out, err := goyaml.Marshal(mirror)
fmt.Printf("Mirror: %s\n%s\nComment:\n%s\n", id, out, mirror.Comment)
return nil
}
示例10: Get
func (c *Conn) Get(data interface{}) error {
id := redisID(data)
redisType := redisType(data)
key := redisKeyWithTypeAndID(redisType, id)
values, err := redis.Values(c.Do("HGETALL", key))
if err != nil {
return err
}
return redis.ScanStruct(values, data)
}
示例11: validateUser
//Validate a user/pass within redis
func validateUser(up userPass) (bool, error) {
ct, err := rds.Do("HINCRBY", up.path(), "attempts", 1)
if err != nil {
return false, err
}
if ct.(int64) > loginAttempts {
rds.Send("MULTI")
rds.Send("HSETNX", up.path(), "reset", time.Now().Add(10*time.Second).Unix())
rds.Send("HGET", up.path(), "reset")
res, err := rds.Do("EXEC")
if err != nil {
return false, err
}
unix, err := strconv.ParseInt(string((res.([]interface{}))[1].([]byte)), 10, 64)
//If the reset time is not in the past, return err
if err == nil && time.Unix(int64(unix), 0).Before(time.Now()) {
defer func() {
//Clear out password attempts
rds.Send("MULTI")
rds.Send("HDEL", up.path(), "reset")
rds.Send("HDEL", up.path(), "attempts")
rds.Do("EXEC")
}()
} else {
if err != nil {
log.Println("login attempt reset error", err)
}
return false, errExceededAttempts
}
}
vals, err := redis.Values(rds.Do("HGETALL", up.path()))
if err != nil || vals == nil {
return false, err
}
var u User
if err := redis.ScanStruct(vals, &u); err != nil {
return false, err
}
bcErr := bcrypt.CompareHashAndPassword(u.Password, []byte(up.Pass))
valid := bcErr == nil
if valid {
defer rds.Do("HDECRBY", up.path(), "attempts", 1)
}
return valid, bcErr
}
示例12: Read
// Read function
func Read(key string, data interface{}) error {
res, _ := redis.Values(conn.Do("HGETALL", key))
if err := redis.ScanStruct(res, data); err != nil {
return err
}
return nil
}
示例13: RetrievePerson
func RetrievePerson(conn redis.Conn, id string) (Person, error) {
var person Person
values, err := redis.Values(conn.Do("HGETALL", fmt.Sprintf("person:%s", id)))
if err != nil {
return person, err
}
err = redis.ScanStruct(values, &person)
return person, err
}
示例14: HGet
func (db *DB) HGet(key string, dest interface{}) error {
defer metrics.MeasureSince([]string{"fn.redis.HGet"}, time.Now())
conn := db.conn()
defer conn.Close()
reply, err := redis.Values(conn.Do("HGETALL", key))
if err != nil {
return err
}
return redis.ScanStruct(reply, dest)
}
示例15: ExampleArgs
func ExampleArgs() {
c, err := dial()
if err != nil {
fmt.Println(err)
return
}
defer c.Close()
var p1, p2 struct {
Title string `redis:"title"`
Author string `redis:"author"`
Body string `redis:"body"`
}
p1.Title = "Example"
p1.Author = "Gary"
p1.Body = "Hello"
if _, err := c.Do("HMSET", redis.Args{}.Add("id1").AddFlat(&p1)...); err != nil {
fmt.Println(err)
return
}
m := map[string]string{
"title": "Example2",
"author": "Steve",
"body": "Map",
}
if _, err := c.Do("HMSET", redis.Args{}.Add("id2").AddFlat(m)...); err != nil {
fmt.Println(err)
return
}
for _, id := range []string{"id1", "id2"} {
v, err := redis.Values(c.Do("HGETALL", id))
if err != nil {
fmt.Println(err)
return
}
if err := redis.ScanStruct(v, &p2); err != nil {
fmt.Println(err)
return
}
fmt.Printf("%+v\n", p2)
}
// Output:
// {Title:Example Author:Gary Body:Hello}
// {Title:Example2 Author:Steve Body:Map}
}