Gorilla/sessions 当 SessionStore 来自导出包时未设置 cookie

Gorilla/sessions cookie not being set when SessionStore is from exported package

我遇到了 gorilla/sessions 的问题。当 sessions.NewCookieStore([]byte("veryprivatekey")) 来自不同的 package/exported 变量时,我的会话没有被保存。

这是有效的:

什么有效

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
}

没有设置cookies。我也尝试过使用 GetStore() 而不是 example.Store,但这也没有用。我应该为每个包裹声明一个 sessions.NewCookieStore 吗?

解决方案是 - 很惊讶我找不到更多关于此的 Whosebug 问题。