I am using golang to build a web backend. Framework and tools I am using are listed as follow:
- Go http://ift.tt/1mOmNL5 as backend
- Go http://ift.tt/1cXjCIV as session manager
- AWS elastic cache as seesion storage
My code is list as follow
package session
import (
"encoding/gob"
"http://ift.tt/1L1lnVB"
"http://ift.tt/1mOmNL5"
"http://ift.tt/1cXjCIV"
"log"
)
const (
//REDIS_HOST = "test-cache.abcde.0001.use1.cache.amazonaws.com"
REDIS_HOST = "localhost"
REDIS_PORT = "6379"
SESSION_KEY = "mypassword"
)
var Store *redistore.RediStore
type SessionType sessions.Session
func init() {
var err error
Store, err = redistore.NewRediStore(10, "tcp", REDIS_HOST+":"+REDIS_PORT, "", []byte(SESSION_KEY))
if err != nil {
log.Fatal(err)
}
Store.SetMaxLength(0) // NOTE: default is 4096
gob.Register(model.MyStruct{}
)
}
func Get(c *gin.Context, name string) *sessions.Session {
s, err := Store.Get(c.Request, name)
if err != nil {
log.Println(err)
}
return s
}
which work perfectly in http request like follow
func Login(c *gin.Context) {
var req map[string]string
errBinding := c.BindWith(&req, binding.JSON)
if errBinding != nil {
c.JSON(400, "request format error")
return
}
uid, _ := // save database get reutn id
var _resp struct {
Success bool `json:"success"`
UID int `json:"uid"`
}
if uid <= 0 {
_resp.Success = false
_resp.UID = uid
c.JSON(200, _resp)
return
} else {
userCookie := cookie.BuildCookie(uid) //set user cookie here
http.SetCookie(c.Writer, userCookie)
s, _ := session.Store.Get(c.Request, "session")
sessions := (*session.SessionType)(s)
sessions.Values["uid"] = uid
err := s.Save(c.Request, c.Writer)
if err != nil {
log.Println(err)
}
_resp.Success = true
_resp.UID = uid
c.JSON(200, _resp)
}
}
func Logout(c *gin.Context) {
s, _ := session.Store.Get(c.Request, "session")
s.Options.MaxAge = -1
s.Save(c.Request, c.Writer)
http.SetCookie(c.Writer, &http.Cookie{
Name: "user",
Path: "/",
Domain: ".mytest.com",
MaxAge: -1,
})
c.String(200, "")
}
My problem is. I want to pop up a message to ask user to relogin, when user long time AFK or session expire? How can I catch session expire event happen? Do I need change front end, add a call that keep send call to check seesion expire or not.
Aucun commentaire:
Enregistrer un commentaire