这个
store
您在主功能中创建的未分配给全局
商店
. 处理程序中使用的全局存储仍然为零。这是因为
:=
运算符起作用,并且您正试图分配给在其他地方声明的var。
你也可以
-
通过不使用
=
声明
var err error
在那条线上
例如
var err error
store, err = mysqlstore.NewMySQLStore(...
-
或者我推荐的方法(没有全局变量)是:初始化
商店
和您所做的一样,还可以通过将处理程序函数包装在一个闭包中并将存储传递到该闭包中来初始化处理程序。
例如
package main
import (
"fmt"
"github.com/srinathgs/mysqlstore"
"net/http"
)
// note: this returns a http.HandlerFunc, which works because
// http.HandlerFunc is just a named type for a function which accepts http.ResponseWriter and *http.Request as args
// see the docs at https://golang.org/pkg/net/http/#HandlerFunc
// (but yea at the end of the day, this is a function which returns another function)
func makeSessTest(store *mysqlstore.MySQLStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
session, err := store.Get(r, "foobar")
session.Values["bar"] = "baz"
session.Values["baz"] = "foo"
err = session.Save(r, w)
fmt.Printf("%#v\n", session)
fmt.Println(err)
}
}
func main() {
store, err := mysqlstore.NewMySQLStore("root:mypass@tcp(127.0.0.1:3306)/mydb?parseTime=true&loc=Local", "sessions", "/", 3600, []byte("<SecretKey>"))
if err != nil {
panic(err)
}
defer store.Close()
http.HandleFunc("/", makeSessTest(store))
http.ListenAndServe(":8080", nil)
}