Exemplo n.º 1
0
func (iter *subscriptionIterator) Value() *subscriptionInfo {
	sub := &subscriptionInfo{}
	reply, _ := redis.Values(iter.conn.Do("HGETALL", iter.values[0]))
	redis.ScanStruct(reply, sub)

	return sub
}
Exemplo n.º 2
0
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
}
Exemplo n.º 3
0
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")
	}
}
Exemplo n.º 4
0
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
}
Exemplo n.º 5
0
// 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

}
Exemplo n.º 6
0
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
		}
	}
}
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
}
Exemplo n.º 8
0
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
}
Exemplo n.º 9
0
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
}
Exemplo n.º 10
0
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)
}
Exemplo n.º 11
0
//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
}
Exemplo n.º 12
0
// 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

}
Exemplo n.º 13
0
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
}
Exemplo n.º 14
0
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)
}
Exemplo n.º 15
0
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}
}
Exemplo n.º 16
0
func (c *StoreClient) FetchRequest(redisKey string) (*Request, error) {
	var fetchedRequest Request

	redisResp, err := redis.Values(c.getConnFromPool().Do("HGETALL", redisKey))
	if err != nil {
		return &fetchedRequest, err
	}

	redis.ScanStruct(redisResp, &fetchedRequest)
	return &fetchedRequest, nil
}
Exemplo n.º 17
0
Arquivo: data.go Projeto: ngc224/colle
func (dm *DataManager) GetItem(keyname string) Item {
	con := dm.Get()
	values, _ := redis.Values(con.Do("HGETALL", keyname))
	itemRedis := ItemRedis{}
	redis.ScanStruct(values, &itemRedis)
	datetime, _ := time.Parse(time.RFC1123Z, itemRedis.PubDate)
	var images []string
	if itemRedis.Images != "" {
		images = strings.Split(itemRedis.Images, "\n")
	}
	return Item{itemRedis, datetime, images}
}
Exemplo n.º 18
0
func (db *DB) HGet(key string, dest interface{}) error {
	m := metrics.GetOrRegisterTimer("fn.redis.HGet", nil)
	defer m.UpdateSince(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)
}
Exemplo n.º 19
0
func RetrieveUrlStats(conn redis.Conn, shortURL string) (UrlStats, error) {
	var stats UrlStats
	rObj, err := redis.Values(conn.Do("HGETALL", shortURL))
	if err != nil {
		log.Printf(err.Error())
		return stats, UrlNotFound
	}
	err = redis.ScanStruct(rObj, &stats)
	if err != nil {
		return stats, err
	}
	return stats, nil
}
Exemplo n.º 20
0
func loadUserInfo(userId string) (*User, error) {

	v, err := redis.Values(conn.Do("HGETALL", "user:"+userId))
	if err != nil {
		return nil, err
	}
	u := &User{Id: userId}
	err = redis.ScanStruct(v, u)
	if err != nil {
		return nil, err
	}
	return u, nil
}
Exemplo n.º 21
0
func NewBlockMeta(rpool *redis.Pool, block_hash string) (blockmeta *BlockMeta, err error) {
	c := rpool.Get()
	defer c.Close()
	blockmeta = new(BlockMeta)
	v, err := redis.Values(c.Do("HGETALL", fmt.Sprintf("block:%v:h", block_hash)))
	if err != nil {
		return
	}
	if err = redis.ScanStruct(v, blockmeta); err != nil {
		return
	}
	return
}
Exemplo n.º 22
0
func (p *Page) load() (err error) {

	c := pool.Get()
	defer c.Close()

	if exists(p.UUID) {
		c.Do("HINCRBY", p.UUID, "Views", 1)
		reply, _ := redis.Values(c.Do("HGETALL", p.UUID))
		redis.ScanStruct(reply, p)
		log.Printf("%s load\n", p.UUID)
	}

	return nil
}
Exemplo n.º 23
0
func AddressBalance(rpool *redis.Pool, address string) (balance uint64, err error) {
	c := rpool.Get()
	defer c.Close()

	addressh := new(AddressHash)
	v, err := redis.Values(c.Do("HGETALL", fmt.Sprintf("addr:%v:h", address)))
	if err != nil {
		panic(err)
	}
	if err := redis.ScanStruct(v, addressh); err != nil {
		panic(err)
	}
	balance = uint64(addressh.TotalReceived - addressh.TotalSent)
	return
}
Exemplo n.º 24
0
func (c *Cache) fetchFileInfoMirror(id, path string) (fileInfo FileInfo, err error) {
	rconn := c.r.pool.Get()
	defer rconn.Close()
	fileInfo.Size = -1
	reply, err := redis.Values(rconn.Do("HGETALL", fmt.Sprintf("FILEINFO_%s_%s", id, path)))
	if err != nil {
		return
	}
	err = redis.ScanStruct(reply, &fileInfo)
	if err != nil {
		return
	}
	c.fimCache.Set(fmt.Sprintf("%s|%s", id, path), &fileInfoValue{value: fileInfo})
	return
}
Exemplo n.º 25
0
func (db *DB) GetUser(uid int) (*User, error) {
	var user User
	c := db.Get()
	defer c.Close()

	r, err := redis.Values(c.Do("HGETALL", "user:"+strconv.Itoa(uid)))
	if err != nil {
		return nil, err
	}

	if err := redis.ScanStruct(r, &user); err != nil {
		return nil, err
	}

	return &user, nil
}
Exemplo n.º 26
0
func HMget(key string) *TagsInfo {
	rc := g.RedisConnPool.Get()
	defer rc.Close()

	v, err := redis.Values(rc.Do("HGETALL", key))
	if err != nil {
		log.Println(err)
		return nil
	}
	p2 := TagsInfo{}
	if err := redis.ScanStruct(v, &p2); err != nil {
		log.Println(err)
		return nil
	}
	return &p2
}
Exemplo n.º 27
0
func (d *dataAccess) GetMetricMetadata(metric string) (*MetricMetadata, error) {
	conn := d.Get()
	defer conn.Close()
	v, err := redis.Values(conn.Do("HGETALL", metricMetaKey(metric)))
	if err != nil {
		return nil, err
	}
	if len(v) == 0 {
		return nil, nil
	}
	mm := &MetricMetadata{}
	if err := redis.ScanStruct(v, mm); err != nil {
		return nil, err
	}
	return mm, nil
}
Exemplo n.º 28
0
Arquivo: db.go Projeto: jodg/niltalk
// Retrieve a map from the db.
func (db *DBconn) GetMap(key string, out interface{}) (bool, error) {
	res, err := redis.Values(db.conn.Do("HGETALL", key))

	if err != nil {
		return false, errors.New("Failed to load from DB")
	}

	// No such entry.
	if len(res) == 0 {
		return false, nil
	}

	redis.ScanStruct(res, out)

	return true, nil
}
Exemplo n.º 29
0
func getPlateTempInCache(serial string, bid int, nid int) (ret *PlateCacheTemp, err error) {
	key := generateKey(serial, bid, nid)
	values, err1 := nfredis.Hgetall(key)
	if err1 != nil {
		return nil, err1
	}
	if len(values) == 0 {
		return nil, nil
	}
	ret = new(PlateCacheTemp)
	err2 := redis.ScanStruct(values, ret)
	if err2 != nil {
		return nil, err2
	}
	return
}
Exemplo n.º 30
0
func FindByUsername(username string) UserModel {
	conn, err := Connect()
	if err != nil {
		log.Println("Connection error:", err)
	}

	conn.Do("SELECT", DB_USER)

	values, _ := redis.Values(conn.Do("HGETALL", username))

	var user UserModel
	if err := redis.ScanStruct(values, &user); err != nil {
		log.Fatal(err)
	}

	return user
}