2017-05-12 23 views
0

我在Golang工作,我正在建立一個API休息,我想知道,我可以使用restful設置cookie嗎? 我正在構建與用戶身份驗證相關的方法:登錄,註銷,註冊等,現在我試圖在生成的uuid響應中設置cookie。我有這樣的:發送cookie在API休息golang

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,所以,如果有可能,怎麼讓它的正確方法?謝謝!

+0

你既可以添加到餅乾的請求,並從響應獲取餅乾。查看文檔:https://golang.org/pkg/net/http/ –

+0

@ william.taylor.09您也可以將Cookie添加到響應中,如鏈接文檔中所示,這是提問者嘗試的內容做。 – Adrian

+0

正確(並且沒有試圖聽起來諷刺,我保證我沒有),用戶完全知道他在這兩個功能鏈接中需要的信息。 –

回答

0

你確實可以設置cookie。

雖然這會讓人覺得它太短了。請記住,REST API只不過是一個HTTP服務器,它具有非常嚴格的應用程序調用方式和返回方式。因此,您可以安全地設置Cookie。

問題是,如果這真的是你應該做的事,看看JSON Web TokensJSON Web Encryption來代替。有兩個Go庫可供使用。通過Cookie使用JWE和JWT的基本原理是您通常希望REST API儘可能無狀態;寧願讓客戶保持狀態。

如果您堅持使用cookies,請考慮使用大猩猩的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"]) 
     } 
    } 
}