04_go-redis、session、cookie

一、redis

go get -u github.com/go-redis/redis


var redisdb *redis.Client

redisdb = redis.New(&redis.Options{

	Addr:"127.0.0.1:6379",

	Password:"",

	DB:0,

})


redisdb.Set("test:name","value",time.Minute * 10)  十分钟失效




二、session

go get github.com/gin-contrib/sessions

import "github.com/gin-contrib/sessions"

2.1、基于redis使用

在main.go 中

import(

	"github.com/gin-contrib/sessions"

	"github.com/gin-contrib/sessions/redis"

)

engine:=gin.Default()

strore,_:=redis.NewStore(10,"tpc","localhost:6379","",[]byte("secret"))

engine.Use(sessions.Sessions("mysession",store))




engine.GET("/path",func(context *gin.Context){

	session:=sessions.Default(context)

	//保存

	num:=16

	session.Set("count",num)

	session.Save()

	//读取

	num=session.Get("count")

})







json.Marshal(member) //将 member 对象序列化

session.Set("user_id",json.Marshal(member))

反序列化

var member Member

sess:=session.Get("user_id")

json.Unmarshal(sess.([]byte),&member)




三、上传图片

file,err:=context.FormFile("file")

filename:="./uploadPath/"+strcov.Format(time.Now().Unix(),10)+file.Filename

err:=context.SaveUploadFile(file,filename)

四、cookie 
//设置cookie
context.SetCookie("cookie_key","val",10*60,"localhost",true,true)
获取cookie
cookie,err:=context.Request.Cookie("cookie_key")

const CookieName="cookie_user"
const CookieTiimeLen=10*60
func CookieAuth(context *gin.Context) (*http.Cookie,error){
  cookie,err:=context.Request.Cookie(CookieName)
  if err==nil{
    context.SetCookie(cookie.Name,cookie.Value,cookie.MaxAge,cookie.Path,cookie.Domain,cookie.Secure,cookie.HttpOnly) 
    return cookie,nil
  }else{
    return nil,err
  }
}