我在使用Gorilla会话处理程序在Golang中持久化会话时遇到问题。其他堆栈溢出问题(此处:Sessions variables in golang not saved while using gorilla sessions和此处:cannot get gorilla session value by key)已提出类似问题(未解决!)。这是非常可怕的,因为似乎1)它不仅仅是我2)似乎没有现在存在的解决方案3)大猩猩会话包可能从根本上被打破。
以下是更详细的问题:
我可以在登录时设置会话没有问题。但是,在我登录后我向后端发出另一个请求时,会话值不会保留,这意味着我无法拉取会话。值['用户名&# 39;]例如(即使这是会话点)。
所以:
A)登录,编写会话,检索会话。值['用户名']并且工作正常。
B)导航到前端的另一个页面并向后端发出另一个请求(创建一个新角色)。
C)尝试检索session.Value ['用户名']。它没有!!!!
以下是用户在后端导航以登录的流程 -
首先是会话处理程序:
package config
import (
"log"
"net/http"
"github.com/gorilla/sessions"
)
type Options struct {
Path string
Domain string
MaxAge int
Secure bool
HttpOnly bool
}
type Session struct {
ID string
Values map[interface{}]interface{}
Options *Options
IsNew bool
}
type Store interface {
Get(r *http.Request, name string) (*sessions.Session, error)
New(r *http.Request, name string) (*sessions.Session, error)
Save(r *http.Request, w http.ResponseWriter, s *sessions.Session) error
}
var SessionsStore = sessions.NewCookieStore([]byte("secret"))
func init() {
SessionsStore.Options = &sessions.Options{
Domain: "localhost",
Path: "/",
MaxAge: 3600 * 8, // 8 hours
HttpOnly: true,
}
}
func KeyStore() (store Store) {
log.Print("inside KeyStore")
store = SessionsStore
log.Print("Value of store is : ", store)
return store
}
接下来,以下是我从main到路由到每个组件的方法:
主要
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"os"
_ "github.com/lib/pq"
"github.com/patientplatypus/gorest/config"
"github.com/gorilla/handlers"
)
const (
host = "localhost"
port = 5432
user = "patientplatypus"
password = "superdupersecretyo"
dbname = "dungeon_world"
)
func main() {
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbname=%s sslmode=disable",
"localhost", 5432, "patientplatypus", "supersecret", "dungeon_world")
var err error
config.DB, err = sql.Open("postgres", psqlInfo)
if err != nil {
panic(err)
}
err = config.DB.Ping()
if err != nil {
panic(err)
}
fmt.Println("Successfully connected~!")
router := NewRouter()
os.Setenv("ORIGIN_ALLOWED", "*")
headersOk := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type"})
originsOk := handlers.AllowedOrigins([]string{os.Getenv("ORIGIN_ALLOWED")})
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
log.Fatal(http.ListenAndServe(":8080", handlers.CORS(originsOk, headersOk, methodsOk)(router)))
}
以下是路由到每个处理程序的路由包:
package main
import (
"net/http"
"github.com/patientplatypus/gorest/users"
"github.com/patientplatypus/gorest/dungeon_db"
"github.com/patientplatypus/gorest/character"
"github.com/patientplatypus/gorest/createcharacter"
"github.com/gorilla/mux"
)
type Route struct {
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
type Routes []Route
func NewRouter() *mux.Router {
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(route.HandlerFunc)
}
return router
}
var routes = Routes{
Route{
"ClassType",
"POST",
"/character/class",
character.ClassType,
},
<MORE ROUTES FOLLOWING SAME PATTERN>
}
现在这是登录功能。这是我编写原始会话并打印出会话的地方。值[&#39;用户名&#39;]表明它有效:
package users
import (
"encoding/json"
"log"
"net/http"
"github.com/patientplatypus/gorest/config"
)
type LoginResponse struct {
Status string
}
type User struct {
Username string
Password string
Id int
}
func UserLogin(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
var incomingjson User
err := decoder.Decode(&incomingjson)
if err != nil {
panic(err)
}
username := incomingjson.Username
password := incomingjson.Password
log.Print("username: ", username)
log.Print("password: ", password)
if username != "" && password != "" {
incomingjson.Login(w, r)
} else {
fmt.Fprintln(w, "error username or password is blank!")
}
}
func (incomingjson *User) Login(w http.ResponseWriter, r *http.Request) {
session, _ := config.KeyStore().Get(r, "cookie-name")
log.Print("loginjson: ", incomingjson)
var tempvar string
err := config.DB.QueryRow("SELECT username FROM users WHERE username=$1;", incomingjson.Username).Scan(&tempvar)
log.Print("err: ", err)
if err == nil {
// 1 row
log.Print("Found username")
var passwordindatabase string
config.DB.QueryRow("SELECT password FROM users WHERE username=$1;", &incomingjson.Username).Scan(&passwordindatabase)
if passwordindatabase == incomingjson.Password {
log.Print("username and password match!")
session.Values["authenticated"] = true
session.Values["username"] = incomingjson.Username
config.KeyStore().Save(r, w, session)
response := LoginResponse{Status: "Success, user logged in"}
json.NewEncoder(w).Encode(response)
} else {
log.Print("username and password don't match!")
session.Values["authenticated"] = false
session.Values["username"] = ""
config.KeyStore().Save(r, w, session)
response := LoginResponse{Status: "Failure, username and password don't match"}
json.NewEncoder(w).Encode(response)
}
} else {
//empty result or error
log.Print("Username not found or there was an error: ", err)
response := LoginResponse{Status: "User not found!"}
json.NewEncoder(w).Encode(response)
}
}
现在这是问题组件。它的工作是在检查用户存在后创建一个新角色(sessioncheck没问题)...
所以我在这里:
package createcharacter
import (
"encoding/json"
"log"
"net/http"
"github.com/patientplatypus/gorest/config"
)
var Username string
var Checkok bool
func SessionsCheck(w http.ResponseWriter, r *http.Request) (username string, checkok bool) {
store := config.KeyStore()
session, _ := store.Get(r, "cookie-name")
log.Print("inside sessionscheck...what is the value of stuff....")
log.Print("session: ", session)
log.Print("session.Values: ", session.Values)
log.Print("username: ", session.Values["username"])
log.Print("authenticated: ", session.Values["authenticated"])
if session.Values["username"] == nil {
if session.Values["authenticated"] == false {
log.Print("Verboten!")
http.Error(w, "Forbidden", http.StatusForbidden)
return "nil", false
}
}
return session.Values["username"].(string), true
}
func NewCharacter(w http.ResponseWriter, r *http.Request) {
Username, Checkok = SessionsCheck(w, r)
<FUNCTION CONTINUES>
这是我收到错误的地方......但我不知道如何修复。
终端输出为:
2017/10/15 15:08:56 inside KeyStore
2017/10/15 15:08:56 Value of store is : &{[0xc42010c000] 0xc42007d5f0}
2017/10/15 15:08:56 inside sessionscheck...what is the value of stuff....
2017/10/15 15:08:56 session: &{ map[] 0xc4201316b0 true 0xc4200e0a80 cookie-name}
2017/10/15 15:08:56 session.Values: map[]
2017/10/15 15:08:56 username: <nil>
2017/10/15 15:08:56 authenticated: <nil>
2017/10/15 15:08:56 http: panic serving [::1]:53668: interface conversion: interface {} is nil, not string
goroutine 13 [running]:
net/http.(*conn).serve.func1(0xc42015c5a0)
/usr/local/opt/go/libexec/src/net/http/server.go:1697 +0xd0
panic(0x133bcc0, 0xc420061f00)
/usr/local/opt/go/libexec/src/runtime/panic.go:491 +0x283
github.com/patientplatypus/gorest/createcharacter.SessionsCheck(0x1540d00, 0xc42010a540, 0xc42014ea00, 0xc42011ab00, 0x3, 0xc420001680)
/Users/patientplatypus/Documents/golang/src/github.com/patientplatypus/gorest/createcharacter/charactercontroller.go:31 +0x5c9
github.com/patientplatypus/gorest/createcharacter.NewCharacter(0x1540d00, 0xc42010a540, 0xc42014ea00)
/Users/patientplatypus/Documents/golang/src/github.com/patientplatypus/gorest/createcharacter/charactercontroller.go:35 +0x5a
net/http.HandlerFunc.ServeHTTP(0x13b8690, 0x1540d00, 0xc42010a540, 0xc42014ea00)
/usr/local/opt/go/libexec/src/net/http/server.go:1918 +0x44
github.com/gorilla/mux.(*Router).ServeHTTP(0xc420066360, 0x1540d00, 0xc42010a540, 0xc42014ea00)
/Users/patientplatypus/Documents/golang/src/github.com/gorilla/mux/mux.go:133 +0xed
github.com/gorilla/handlers.(*cors).ServeHTTP(0xc42010c7e0, 0x1540d00, 0xc42010a540, 0xc42014e800)
/Users/patientplatypus/Documents/golang/src/github.com/gorilla/handlers/cors.go:118 +0x5c8
net/http.serverHandler.ServeHTTP(0xc42014a000, 0x1540d00, 0xc42010a540, 0xc42014e800)
/usr/local/opt/go/libexec/src/net/http/server.go:2619 +0xb4
net/http.(*conn).serve(0xc42015c5a0, 0x1541240, 0xc420061dc0)
/usr/local/opt/go/libexec/src/net/http/server.go:1801 +0x71d
created by net/http.(*Server).Serve
/usr/local/opt/go/libexec/src/net/http/server.go:2720 +0x288
我很遗憾详细说明,但我认为这是我可以从我的代码库中重现的最小例子。如果有人有任何建议,请告诉我。
编辑:
我注意到的一件事是:
2017/10/15 15:08:56 session: &{ map[] 0xc4201316b0 true 0xc4200e0a80 cookie-name}
2017/10/15 15:08:56 session.Values: map[]
似乎表示用户名和经过身份验证的(真正的0xc4200e0a80)存储在session.Values [] map函数的之外。那是为什么?
编辑编辑:
所以......我认为我编写config.KeyStore()的方式可能是一个问题,所以我把它改写成以下内容并在整个项目中保留它:
package config
import (
"github.com/gorilla/sessions"
)
var SessionsStore = sessions.NewCookieStore([]byte("secret"))
func init() {
SessionsStore.Options = &sessions.Options{
Domain: "localhost",
Path: "/",
MaxAge: 3600 * 8, // 8 hours
HttpOnly: true,
}
}
所以现在我需要SessionsStore,我只需要调用conf.SessionsStore。这似乎是我认为可行的方法。我仍然有同样的问题。
答案 0 :(得分:1)
package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/gorilla/sessions"
)
const appCookie = "myappcookies"
var cookies *sessions.CookieStore
func Login(w http.ResponseWriter, r *http.Request) {
//
// For the sake of simplicity, I am using a global here.
// You should be using a context.Context instead!
session, err := cookies.Get(r, appCookie)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Println(err)
return
}
session.Values["userName"] = "StackOverflow"
session.Save(r, w)
}
func Session(w http.ResponseWriter, r *http.Request) {
session, err := cookies.Get(r, appCookie)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Println(err)
return
}
w.Write([]byte(fmt.Sprintf("Objects in session: %d\n", len(session.Values))))
for k, v := range session.Values {
w.Write([]byte(fmt.Sprintf("Key=%v, Value=%v\n", k, v)))
}
}
func main() {
cookies = sessions.NewCookieStore([]byte("mysuperdupersecret"))
router := mux.NewRouter()
router.Path("/login").Methods(http.MethodPost).HandlerFunc(Login)
router.Path("/session").Methods(http.MethodGet).HandlerFunc(Session)
server := &http.Server{
Handler: router,
Addr: ":8000",
// Good practice: enforce timeouts for servers you create!
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
log.Fatal(server.ListenAndServe())
}