英文:
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会话管理器。因此,你需要自己编写一个,或者使用其他人编写的会话管理器。
以下是一些示例:
- https://github.com/icza/session - 包括Google App Engine支持(声明:我是作者)
- https://github.com/gorilla/sessions(Gorilla Web Toolkit的一部分)
通常,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:
- https://github.com/icza/session - includes Google App Engine support (disclosure: I'm the author)
- https://github.com/gorilla/sessions (part of the Gorilla web toolkit)
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论