Undefined return type in Go

huangapple go评论99阅读模式
英文:

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需要知道在哪个包中找到Sessionsessions.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) {
  ...
}

huangapple
  • 本文由 发表于 2016年4月5日 06:39:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/36414145.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定