获取会话值

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

Get session values

问题

我的Rails应用程序使用会话来存储用户凭据以进行授权。我正在尝试在Go代码中登录并执行一些需要用户会话的操作。在登录时,我应该检索用户会话并传递给下一个请求吗?我该如何处理这个问题?

英文:

My rails app uses session for storing a user credentials for authorization. Trying to sign in and do some actions (that require a user session) in Go code. Should I retrieve a user session when signing in and pass to the next request? How can I handle that?

答案1

得分: 9

Go的标准库没有提供HTTP会话管理器。因此,你需要自己编写一个,或者使用其他人编写的会话管理器。

以下是一些示例:

通常,HTTP会话是通过服务器和客户端之间的cookie进行管理的,因此会话(会话ID)可以直接从请求(http.Request)中获取,例如使用Request.Cookie()

也就是说,不需要通过“请求链”来“传递”会话,每个处理程序只需通过http.Request即可访问它。

例如,使用github.com/icza/session可以这样做:

func MyHandler(w http.ResponseWriter, r *http.Request) {
    sess := session.Get(r)
    if sess == nil {
        // 没有会话(尚未创建)
    } else {
        // 我们有一个会话,使用它
    }
}

使用Gorilla sessions,类似的方式:

var store = sessions.NewCookieStore([]byte("something-very-secret"))

func MyHandler(w http.ResponseWriter, r *http.Request) {
    session, err := store.Get(r, "session-name")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    // 使用会话
}
英文:

Go's standard library does not provide an HTTP session manager. So you have to write one yourself, or use one written by others.

Some examples:

Usually HTTP sessions are managed via cookies between server and client, and as such, the session (session id) can be acquired directly from the request (http.Request) e.g. with Request.Cookie().

That being said it is not necessary to "pass" the session through the "request chain", every handler can access it just by having the http.Request.

For example using github.com/icza/session it can be done like this:

func MyHandler(w http.ResponseWriter, r *http.Request) {
	sess := session.Get(r)
	if sess == nil {
		// No session (yet)
	} else {
		// We have a session, use it
	}
}

Using Gorilla sessions, it's similar:

var store = sessions.NewCookieStore([]byte("something-very-secret"))

func MyHandler(w http.ResponseWriter, r *http.Request) {
	session, err := store.Get(r, "session-name")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	// Use session
}

huangapple
  • 本文由 发表于 2016年9月15日 19:25:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/39509914.html
匿名

发表评论

匿名网友

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

确定