我试图将我的数据库对象传递给我的处理程序,而不是拥有一个全局对象.但我不知道这是否可行,我正在使用Gorilla Mux包,我可以看到它需要一个封闭作为第二个参数.
// https://github.com/gorilla/mux/blob/master/mux.go#L174
// HandleFunc registers a new route with a matcher for the URL path.
// See Route.Path() and Route.HandlerFunc().
func (r *Router) HandleFunc(path string, f func(http.ResponseWriter,
*http.Request)) *Route {
return r.NewRoute().Path(path).HandlerFunc(f)
}
Run Code Online (Sandbox Code Playgroud)
然后定义了我可以使用的参数,理想情况下我希望有这样的第三个参数.
// In my main
router.HandleFunc("/users/{id}", showUserHandler).Methods("GET")
func showUserHandler(w http.ResponseWriter, r *http.Request, db *gorm.DB) {
fmt.Fprintf(w, "We should fetch the user with id %s", vars["id"])
}
Run Code Online (Sandbox Code Playgroud)
有解决方法吗?或者我需要一个全局数据库对象?我是Go的新手,所以请详细解释一个可能的答案.
使用gorilla sessions Web工具包时,不会跨请求维护会话变量.当我启动服务器并输入localhost时:8100/page被定向到login.html,因为会话值不存在.登录后,我在商店中设置了会话变量,页面被重定向到home.html.但是当我打开一个新选项卡并输入localhost:8100时,应该使用已存储的会话变量将页面定向到home.html,但页面会被重定向到login.html.以下是代码.
package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
"github.com/gocql/gocql"
"github.com/gorilla/mux"
"github.com/gorilla/sessions"
"net/http"
"time"
)
var store = sessions.NewCookieStore([]byte("something-very-secret"))
var router = mux.NewRouter()
func init() {
store.Options = &sessions.Options{
Domain: "localhost",
Path: "/",
MaxAge: 3600 * 1, // 1 hour
HttpOnly: true,
}
}
func main() {
//session handling
router.HandleFunc("/", SessionHandler)
router.HandleFunc("/signIn", SignInHandler)
router.HandleFunc("/signUp", SignUpHandler)
router.HandleFunc("/logOut", LogOutHandler)
http.Handle("/", router)
http.ListenAndServe(":8100", nil)
}
//handler for signIn
func SignInHandler(res http.ResponseWriter, req *http.Request) {
email := req.FormValue("email")
password := req.FormValue("password")
//Generate hash …Run Code Online (Sandbox Code Playgroud)