从导出的程序包获取SessionStore时未设置大猩猩/会话cookie

时间:2019-05-03 00:43:35

标签: go gorilla

我遇到gorilla/sessions的问题。 sessions.NewCookieStore([]byte("veryprivatekey"))来自不同的包/导出变量时,不会保存我的会话。

这是有效的方法:

什么有效

exampleproj / main.go

package main

import (
    "fmt"
    "github.com/gorilla/mux"
    "github.com/gorilla/sessions"
    "net/http"
)

var store *sessions.CookieStore
var cookie_name = "sess"


func main() {
    store = sessions.NewCookieStore([]byte("veryprivatekey"))
    router := mux.NewRouter()
    router.HandleFunc("/cookietest", cookietest)
    router.HandleFunc("/cookietest2", cookietest2)
    err := http.ListenAndServe(":8080", router)
    if err != nil {
        fmt.Print(err)
    }
}

var cookietest = func(w http.ResponseWriter, r *http.Request) {
    session, err := store.Get(r, cookie_name)
    if err != nil {
        fmt.Println(err)
    }
    session.Values["Stack"] = "Overflow"
    err = session.Save(r,w)
    if err != nil {
        fmt.Println(err)
    }
}

var cookietest2 = func(w http.ResponseWriter, r *http.Request) {
    session, err := store.Get(r, cookie_name)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println("Stack: ", session.Values["Stack"])
}

(打开localhost:8080 / cookietest并检查是否已创建cookie)

问题

以下是sessions.CookieStore来自另一个软件包的一些代码:

exampleproj / main.go

package main

import (
    "expirements/example"
    "fmt"
    "github.com/gorilla/mux"
    "net/http"
)

var cookie_name = "sess"


func main() {
    router := mux.NewRouter()
    router.HandleFunc("/cookietest", cookietest)
    router.HandleFunc("/cookietest2", cookietest2)
    err := http.ListenAndServe(":8080", router)
    if err != nil {
        fmt.Print(err)
    }
}

var cookietest = func(w http.ResponseWriter, r *http.Request) {
    session, err := example.Store.Get(r, cookie_name)
    if err != nil {
        fmt.Println(err)
    }
    session.Values["Stack"] = "Overflow"
    err = session.Save(r,w)
    if err != nil {
        fmt.Println(err)
    }
}

var cookietest2 = func(w http.ResponseWriter, r *http.Request) {
    session, err := example.Store.Get(r, cookie_name)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println("Stack: ", session.Values["Stack"])
}

exampleproj / example / ex.go

package example

import (
    "github.com/gorilla/sessions"
)

var Store *sessions.CookieStore

func init() {
    Store = sessions.NewCookieStore([]byte("veryprivatekey"))
    Store.Options = &sessions.Options{
        //Domain:   config.Host,
        //Path:     "/",
        MaxAge:   259200,
        Secure:   true,
        HttpOnly: true,
    }
}

func GetStore() *sessions.CookieStore {
    return Store
}

未设置Cookie。我也尝试使用GetStore()代替example.Store,但是那也不起作用。我应该为每个包装声明一个sessions.NewCookieStore吗?

1 个答案:

答案 0 :(得分:0)

解决方案是here-令人惊讶的是我找不到更多有关此问题的堆栈溢出问题。