gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:19:39 25 4
gpt4 key购买 nike

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

这是有效的:

什么有效

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 吗?

最佳答案

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

关于当 SessionStore 来自导出包时未设置 Gorilla/sessions cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55961927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com