英文:
Undefined return type in Go
问题
我对Go语言还比较新,遇到了一个使用mux-gorilla sessions/cookies的代码片段的问题。这段代码有很多冗余的部分,我想通过下面的函数来减少冗余:
func isLoggedIn(w http.ResponseWriter, r *http.Request) (bool, *Session) {
session, err := store.Get(r, "user")
var logged bool = true
if err != nil { // 需要删除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函数可以返回Session类型,为什么会出现未定义的错误呢?请注意,之前已经使用了store = sessions.NewCookieStore([]byte(secret))
来声明了store,使用了"gorilla/sessions"包。
英文:
I'm fairly new to Go and am having trouble with a code snippet that uses mux-gorilla sessions/cookies. There is a lot of redundancy that I would like to reduce with the following function:
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
}
Unfortunately I get the following compilation error: undefined: Session
How can this type be undefined if it can be returned by the store.Get function? Note that store was declared before as store = sessions.NewCookieStore([]byte(secret))
, using the "gorilla/sessions" package.
答案1
得分: 3
Go需要知道在哪个包中找到Session
:sessions.Session
。
错误出现在你的isLoggedIn
函数的签名上。
所以你修改后的代码应该是:
import "github.com/gorilla/sessions"
func isLoggedIn(w http.ResponseWriter, r *http.Request) (bool, *sessions.Session) {
...
}
英文:
Go needs to know which package to find Session
in: sessions.Session
.
The error is on the signature of your func isLoggedIn
So your modified code would be:
import "github.com/gorilla/sessions"
func isLoggedIn(w http.ResponseWriter, r *http.Request) (bool, *sessions.Session) {
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论