在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!

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