github.com/zooyer/miskit@v1.0.71/micro/session_test.go (about) 1 package micro 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "net/http" 7 "testing" 8 9 "github.com/gin-contrib/sessions" 10 "github.com/gin-gonic/gin" 11 "github.com/stretchr/testify/assert" 12 _ "github.com/zooyer/miskit/imdb/driver/buntdb" 13 _ "github.com/zooyer/miskit/imdb/driver/redis" 14 ) 15 16 func TestNewStore(t *testing.T) { 17 store, err := NewStore("redis", "", "", []byte("test")) 18 if err != nil { 19 t.Fatal(err) 20 } 21 22 session := sessions.Sessions("miskit-test", store) 23 24 engine := gin.Default() 25 engine.Use(session) 26 27 engine.GET("/set", func(ctx *gin.Context) { 28 session := sessions.Default(ctx) 29 session.Set(ctx.Query("key"), ctx.Query("value")) 30 if err := session.Save(); err != nil { 31 ctx.String(http.StatusInternalServerError, err.Error()) 32 ctx.Abort() 33 return 34 } 35 36 ctx.String(http.StatusOK, "ok") 37 }) 38 39 engine.GET("/get", func(ctx *gin.Context) { 40 session := sessions.Default(ctx) 41 value := session.Get(ctx.Query("key")) 42 ctx.String(http.StatusOK, "%s", value) 43 }) 44 45 const ( 46 key = "name" 47 value = "张三" 48 ) 49 50 resp := get(engine, fmt.Sprintf("/set?key=%s&value=%s", key, value)) 51 data, _ := ioutil.ReadAll(resp.Body) 52 assert.Equal(t, http.StatusOK, resp.Code) 53 assert.Equal(t, "ok", string(data)) 54 55 cookie := resp.Header().Get("Set-Cookie") 56 resp = get(engine, fmt.Sprintf("/get?key=%s", key), http.Header{ 57 "Cookie": {cookie}, 58 }) 59 data, _ = ioutil.ReadAll(resp.Body) 60 assert.Equal(t, http.StatusOK, resp.Code) 61 assert.Equal(t, value, string(data)) 62 }