func JobsCount(userid string) int { c := redisPool.Get() defer c.Close() hc := hdis.Conn{c} count, _ := redis.Int(hc.Do("HGET", "u:"+userid+":jobs")) return count }
func (user *User) Profile(attribute string) string { conn := RedisPool.Get() defer conn.Close() hc := hdis.Conn{conn} attr, _ := redis.String(hc.Get("u:" + user.Id + ":" + strings.ToLower(attribute))) return attr }
func (user *User) PreLogin(c *Context) error { if user.Id != "" { conn := RedisPool.Get() defer conn.Close() hc := hdis.Conn{conn} previousPicture, _ = redis.String(hc.Get("u:" + user.Id + ":picture")) } return nil }
func (p *Project) save() error { c := redisPool.Get() defer c.Close() hc := hdis.Conn{c} // Decrease number of jobs and remove it from the queue defer hc.Do("HINCRBY", "u:"+p.OwnerId+":jobs", -1) defer c.Do("SREM", "jobs-in-queue", p.Id) log.Printf("Saving project %q, %q", p.Id, p.URL) err := p.generateThumbnail() if err != nil { log.Println(err) } p.Thumb = err == nil var buffer bytes.Buffer enc := gob.NewEncoder(&buffer) err = enc.Encode(p) if err != nil { return err } key := "p:" + p.Id _, err = hc.Set(key, buffer.Bytes()) if err != nil { return err } _, err = c.Do("RPUSH", "u:"+p.OwnerId, p.Id) if err != nil { return err } _, err = c.Do("LPUSH", "recent-projects", p.Id) if err != nil { return err } for _, tag := range p.Tags { tag = strings.ToLower(strings.TrimSpace(tag)) c.Do("SADD", "t:"+tag, p.Id) } log.Printf("Saved project %q, %q", p.Id, p.URL) return nil }
func Fetch(pId string) (*Project, error) { c := redisPool.Get() defer c.Close() var project Project hc := hdis.Conn{c} p, err := redis.Bytes(hc.Get("p:" + pId)) if err != nil { return nil, err } buffer := bytes.NewBuffer(p) dec := gob.NewDecoder(buffer) dec.Decode(&project) return &project, nil }
func (p *Project) Delete() error { projectsPath := path.Join(appRoot, "static", "projects") imgPath := path.Join(projectsPath, p.OwnerId, p.Id) err := os.RemoveAll(imgPath) if err != nil { return err } // Delete the owner directory if it's empty, so any errors should be ignored ownerPath := path.Join(projectsPath, p.OwnerId) os.Remove(ownerPath) c := redisPool.Get() defer c.Close() hc := hdis.Conn{c} _, err = c.Do("LREM", "u:"+p.OwnerId, 1, p.Id) if err != nil { return err } _, err = c.Do("LREM", "recent-projects", 1, p.Id) if err != nil { return err } for _, tag := range p.Tags { tag = strings.ToLower(strings.TrimSpace(tag)) c.Do("SREM", "t:"+tag, p.Id) } key := "p:" + p.Id if deleted, _ := redis.Bool(hc.Do("HDEL", key)); deleted { return nil } return ProjectDeleteError }
func (p *Project) Save() error { _, err := url.ParseRequestURI(p.URL) if err != nil { return InvalidUrlError } c := redisPool.Get() defer c.Close() hc := hdis.Conn{c} // Use a short project id and double checked for it's existance for { p.Id = utils.GenId(3) key := "p:" + p.Id if exists, _ := redis.Bool(hc.Do("HEXISTS", key)); !exists { break } } if ok, _ := redis.Bool(c.Do("SADD", "jobs-in-queue", p.Id)); ok { hc.Do("HINCRBY", "u:"+p.OwnerId+":jobs", 1) j := job{project: p, err: make(chan error)} // Put the job in the queue, this will block if it's full saveQueue <- j // Read the result from err channel return <-j.err } return ProjectSaveError }
func newContext(w http.ResponseWriter, r *http.Request) (*Context, error) { context := &Context{Response: w, Request: r} // Create a session and store it in cookie so that we can recognize the user when he/she gets back // TODO: read session/cookie name from config var err error context.Session, err = sessionStore.Get(r, "gapp") if err != nil { log.Printf("error in getting session store: %q", err) } // Changed maximum age of the session to one month context.Session.Options = &sessions.Options{ Path: "/", MaxAge: 86400 * 30, } // Generate new userid if there isn't any userid, ok := context.Session.Values["userid"].(string) if !ok { // It's an anonymous user userid = utils.GenId(16) context.Session.Values["userid"] = userid } else { // Let's fetch user's profile conn := RedisPool.Get() defer conn.Close() hc := hdis.Conn{conn} key := "u:" + userid + ":gob" if ok, _ := redis.Bool(hc.Do("HEXISTS", key)); ok { u, err := redis.Bytes(hc.Get(key)) if err == nil { var user *User buffer := bytes.NewBuffer(u) dec := gob.NewDecoder(buffer) err = dec.Decode(&user) if err == nil { context.User = user } else { log.Printf("error in decoding user's (%s) profile: %q", userid, err) } } else { log.Printf("error in fetching user's (%s) profile from redis: %q", userid, err) } } } if context.User == nil { context.User = &User{Id: userid, Name: "Anonymous"} } // Saving session everytime it gets access helps to push expiry date further err = context.Session.Save(r, w) return context, err }
func ExampleGet() { c, _ := redis.Dial("tcp", ":6379") defer c.Close() hc := hdis.Conn{c} key := "object:1234567" hc.Set(key, "The value") value, _ := redis.String(hc.Get(key)) fmt.Printf("%v\n", value) // Delete the hash if it exists if exists, _ := redis.Bool(hc.Do("HEXISTS", key)); exists { _, err := hc.Do("HDEL", key) if err != nil { fmt.Println(err) } } // Execute invalid hash command _, err := hc.Do("GET", "sample-key") if err == hdis.NotAHashCommandError { fmt.Println("Invalid hash command") } else { fmt.Println(err) } // Output: // The value // Invalid hash command }
func (user *User) Login(c *Context) error { conn := RedisPool.Get() defer conn.Close() hc := hdis.Conn{conn} user.Id, _ = redis.String(conn.Do("ZSCORE", "users", user.Email)) if user.Id == "" { // Yay another newcomer! nextuserid, err := conn.Do("INCR", "next-user-id") if err != nil { return err } // Pad userid with 0 user.Id = fmt.Sprintf("%03d", nextuserid.(int64)) _, err = conn.Do("ZADD", "users", user.Id, user.Email) if err != nil { return err } } else { // Pad user.Id with 0 user.Id = fmt.Sprintf("%03s", user.Id) } err := user.PreLogin(c) if err != nil { return err } // Signin the user user.SignedIn = true // Encode to gob var buffer bytes.Buffer enc := gob.NewEncoder(&buffer) err = enc.Encode(user) if err != nil { return err } // Every time set the user's info, actually it'll update the profile key := "u:" + user.Id + ":gob" _, err = hc.Set(key, buffer.Bytes()) if err != nil { return err } keys := []string{"Name", "GivenName", "FamilyName", "Email", "Gender", "Picture", "Birthday"} for _, key := range keys { rediskey := "u:" + user.Id + ":" + strings.ToLower(key) _, err = hc.Set(rediskey, reflect.ValueOf(user).Elem().FieldByName(key).String()) if err != nil { return err } } err = user.PostLogin(c) return err }