我在 Golang 工作,我正在构建一个 API-Rest 并且想知道,我可以使用 restful 设置 cookies 吗? 我正在构建与用户身份验证相关的方法:登录、注销、注册等,现在我正在尝试使用生成的 uuid 在响应中设置 cookie。我有这个:
func Login(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
...some code....
c := &http.Cookie{
Name: "session",
Value: uuid.NewV4().String(),
}
http.SetCookie(w, c)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
json.NewEncoder(w).Encode(user)
w.WriteHeader(fasthttp.StatusOK)
}
但是在响应中我没有得到任何 cookie,所以,如果可能的话,正确的制作方法是什么?谢谢!
最佳答案
你确实可以设置cookies。
不过,这似乎是一个太短的答案。请记住,REST API 只不过是一个 HTTP 服务器,对其调用方式和返回内容有非常严格的使用。因此,您可以安全地设置 cookie。
但问题是,如果这真的是您应该做的事情,请查看 JSON Web Tokens和 JSON Web Encryption反而。两者都有可用的 Go 库。在 cookie 上使用 JWE 和 JWT 的基本原理是您通常希望 REST API 尽可能无状态;更喜欢客户端保持状态。
如果您坚持使用 cookie,请考虑使用 Gorilla 的 securecookie API,因为您可能不希望人们偷看您的 cookie 的内容。您可以这样使用它:
import "github.com/gorilla/securecookie"
s := securecoookie.New([]byte("very-secret-1234"), byte[]("much-hidden-5678"))
func SetCookieHandler(w http.ResponseWriter, r *http.Request) {
value := map[string]string{
"foo": "bar",
}
if encoded, err := s.Encode("cookie-name", value); err == nil {
cookie := &http.Cookie{
Name: "cookie-name",
Value: encoded,
Path: "/",
Secure: true,
HttpOnly: true,
}
http.SetCookie(w, cookie)
}
}
同样,您可以像这样检索 Cookie 的内容:
func ReadCookieHandler(w http.ResponseWriter, r *http.Request) {
if cookie, err := r.Cookie("cookie-name"); err == nil {
value := make(map[string]string)
if err = s2.Decode("cookie-name", cookie.Value, &value); err == nil {
fmt.Fprintf(w, "The value of foo is %q", value["foo"])
}
}
}
关于rest - 在 API Rest golang 中发送 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43945042/