0

我对 Go 还很陌生,并且在使用 mux-gorilla 会话/cookie 的代码片段时遇到了麻烦。我想通过以下功能减少很多冗余:

func isLoggedIn(w http.ResponseWriter, r *http.Request) (bool, *Session) {
    session, err := store.Get(r, "user")
    var logged bool = true
    if err != nil { // Need to delete the cookie.
        expired := &http.Cookie{Path: "/", Name: "user", MaxAge: -1, Expires: time.Now().Add(-100 * time.Hour)}
        http.SetCookie(w, expired)
        logged := false
    }
    return logged, session
}

不幸的是,我收到以下编译错误:undefined: Session

如果 store.Get 函数可以返回这种类型,怎么可能是 undefined 呢?请注意,之前store = sessions.NewCookieStore([]byte(secret))使用“gorilla/sessions”包将 store 声明为 。

4

1 回答 1

3

Go 需要知道要在哪个包中找到Sessionsessions.Session.

错误在您的函数的签名上isLoggedIn

因此,您修改后的代码将是:

import "github.com/gorilla/sessions"
func isLoggedIn(w http.ResponseWriter, r *http.Request) (bool, *sessions.Session) {
  ...
}
于 2016-04-04T22:42:45.850 回答