doulei1965 2017-05-12 19:20
浏览 14

在API Rest golang中发送cookie

am working in Golang, I am building an API-Rest and am wondering, can I set cookies using restful? I am building the methos related to the authentication of the users: login, logout,sign up, etc. and by now am trying to set a cookie in the response with the generated uuid. I have this:

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)
}

But in the response I don't get any cookie, so, if is possible, how is the proper way to make it? Thank you!

  • 写回答

1条回答 默认 最新

  • dqcuq4138 2017-05-12 22:22
    关注

    You can indeed set cookies.

    This would feel like it's too short of an answer though. Remember that a REST API is nothing more than a HTTP server with a very strict usage of how it should be called and what it returns. As such, you can safely set cookies.

    The question is though, if that is really something you should do, have a look at JSON Web Tokens and JSON Web Encryption instead. There are Go libraries available for both. The rationale for using JWE and JWT over cookies is that you usually want a REST API to be as stateless as possible; preferring for the Client to keep state instead.

    If you insist on using cookies though, consider using Gorilla's securecookie API instead, as you probably do not want people peeking into your cookie's contents. You can use it as so:

    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)
        }
    }
    

    Similarly, you can retrieve the Cookie's contents like this:

    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"])
            }
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c