1
0
Fork 0
empact/server/session.go

49 lines
948 B
Go
Raw Normal View History

2015-03-05 15:04:44 +00:00
package server
import (
"net/http"
"time"
"code.google.com/p/go-uuid/uuid"
"github.com/garyburd/redigo/redis"
)
const (
2015-03-06 12:36:35 +00:00
cookieName = "session_id"
2015-03-05 15:04:44 +00:00
)
var (
2015-03-06 12:36:35 +00:00
redisPool = redis.NewPool(dialRedis, 10)
2015-03-05 15:04:44 +00:00
)
func sessionHandler(w http.ResponseWriter, r *http.Request) {
2015-03-06 12:36:35 +00:00
if cook, err := r.Cookie(cookieName); err != nil {
2015-03-05 15:04:44 +00:00
cook = &http.Cookie{
2015-03-06 12:36:35 +00:00
Name: cookieName,
2015-03-05 15:04:44 +00:00
Value: uuid.New(),
Path: "/",
Expires: time.Now().Add(365 * 24 * time.Hour),
HttpOnly: true,
}
http.SetCookie(w, cook)
}
}
2015-03-06 12:36:35 +00:00
func createSession(r *http.Request, login string) {
redisPool.Get().Do("HSET", "sessions", sessionID(r), login)
}
2015-03-05 15:04:44 +00:00
func sessionID(r *http.Request) string {
2015-03-06 12:36:35 +00:00
cook, _ := r.Cookie(cookieName)
2015-03-05 15:04:44 +00:00
return cook.Value
}
2015-03-06 12:36:35 +00:00
func sessionUser(r *http.Request) (login string) {
login, _ = redis.String(redisPool.Get().Do("HGET", "sessions", sessionID(r)))
2015-03-06 11:18:15 +00:00
return
2015-03-05 15:04:44 +00:00
}
2015-03-06 12:36:35 +00:00
func dialRedis() (redis.Conn, error) {
return redis.Dial("tcp", ":6379")
2015-03-05 15:04:44 +00:00
}