使用gin,gin-contrib/sessions不同request path獲取不到session

adolphlwq發表於2017-08-04

gin session problem

從開發環境中抽出來了 sample code,https://github.com/dockerq/gin-session-problem,歡迎下載測試、重現問題。

環境

  1. gin 版本 { "checksumSHA1": "86tapazS8gfJ5JRCxVNTTDkUZwM=", "path": "github.com/gin-gonic/gin", "revision": "bbd4dfee5056087c640a75c6cc21567f4f47585d", "revisionTime": "2017-07-12T07:01:46Z" }
  2. golang 1.8.0
  3. gin 中設定 session 程式碼

    r := gin.Default()
    
    store := sessions.NewCookieStore([]byte("secret"))
    store.Options(sessions.Options{
        MaxAge: int(30 * time.Minute), //30min
        Path:   "/",
    })
    
    r.Use(sessions.Sessions("mysession", store))
    r.GET("/pre", preSession)
    r.GET("/do", DoSomethine)
    r.Run(":8081")
    fmt.Println("start api server success.")
    
  4. preSession(這個函式目的是向啟動的 gin.Engine 中新增一條 session 記錄)

    func preSession(c *gin.Context) {
    session := sessions.Default(c)
    session.Set("test@mail.com", "test.access.token")
    session.Save()
    c.JSON(http.StatusOK, nil)
    }
    
  5. DoSomethine 函式接受 email 引數,讀取 session 中對應 email 的 value

    func DoSomethine(c *gin.Context) {
    userEmail := c.Query("user_email")
    if userEmail == "" {
        panic("can not get user email")
    }
    session := sessions.Default(c)
    userAccessToken := session.Get(userEmail)
    fmt.Printf("[DoSomethine] user access token is %s\n", userAccessToken)
    c.JSON(http.StatusOK, nil)
    }
    
  6. 測試方法,先呼叫 getPreSession() 設定一條 session,然後訪問/do檢視是否拿到 session。

    func TestSession(t *testing.T) {
    StartTestServer(t)
    getPreSession()
    
    u := url.Values{}
    u.Set("user_email", "test@mail.com")
    testUrl := apiBaseUrl + "/do?" + u.Encode()
    fmt.Printf("test url is %s\n", testUrl)
    
    resp, err := http.Get(testUrl)
    defer resp.Body.Close()
    
    if err != nil {
        t.Error(err)
    }
    
    fmt.Println(resp.StatusCode)
    }
    
  7. 結果,注意[DoSomethine] user access token is %! s(<nil>)表明沒有拿到 session。

    ➜  session make test 
    go test --cover -test.v
    === RUN   TestSession
    cookie of pre session request is [mysession=MTUwMTgxNDYxNnxEdi1CQkFFQ180SUFBUkFCRUFBQU9QLUNBQUVHYzNSeWFXNW5EQThBRFhSbGMzUkFiV0ZwYkM1amIyMEdjM1J5YVc1bkRCTUFFWFJsYzNRdVlXTmpaWE56TG5SdmEyVnV8cc0AwUddF90uWUxOF8BONUo-tFGouRdSOfj62m9U8sE=; Path=/; Expires=Wed, 09 Jan 1771 04:16:32 GMT; Max-Age=1800000000000]
    test url is http://0.0.0.0:8081/do?user_email=test%40mail.com
    [DoSomethine] user access token is %!s(&lt;nil&gt;)
    [GIN] 2017/08/04 - 10:43:36 | 200 |      99.642µs |       127.0.0.1 |  GET     /do
    200
    --- PASS: TestSession (2.00s)
        main_test.go:36: waiting 2 second for server startup
    PASS
    coverage: 48.0% of statements
    ok      ginlab/session  2.010s
    

問題

為什麼/pre設定 session 後,請求/do卻拿不到 session?是沒 session 沒有配置正確還是其它原因?

更多原創文章乾貨分享,請關注公眾號
  • 使用gin,gin-contrib/sessions不同request path獲取不到session
  • 加微信實戰群請加微信(註明:實戰群):gocnio

相關文章