doutang7383
2019-07-12 17:10
浏览 87
已采纳

无法在标题中设置Cookie

I am trying to set cookies from Go web server and then reading it in the chrome browser.

Here is my code

package main

import (
    "fmt"
    "net/http"
    "time"
)


func setCookies(w http.ResponseWriter, r *http.Request){
    expiration := time.Now().Add(365 * 24 * time.Hour)
    c1 := http.Cookie{Name: "SpiderMan: Far from home",Value : "HollyWood", Path: "/", Expires: expiration, Secure: false}
    http.SetCookie(w,&c1)
    c2 := http.Cookie{Name: "Kabir Singh",Value: "BollyWood", Path: "/", Expires: expiration, Secure: false}
    http.SetCookie(w,&c2)

    // w.Header().Set("Set-Cookie",c1.String())
    // w.Header().Add("Set-Cookie",c2.String())
    // HttpOnly: true

    fmt.Fprintf(w, "")

}

func getCookies(w http.ResponseWriter, r *http.Request){
    // h := r.Header["Kabir Singh"]
    // fmt.Fprintln(w,h)

    c1, err := r.Cookie("Kabir Singh")
    if err != nil {
        fmt.Fprintln(w, "first_cookie is not set successfully." ,err)
    }
    ca := r.Cookies()
    fmt.Fprintln(w, c1)
    fmt.Fprintln(w, ca)
}

func main() {
    server := http.Server{
        Addr: "127.0.0.1:2020",
    }
    http.HandleFunc("/set_cookies", setCookies)
    http.HandleFunc("/get_cookies", getCookies)
    server.ListenAndServe()
}

After setting the cookies from call set_cookies when I am trying to get the cookies in the chrome browser I get this output:

first_cookie is not set successfully. http: named cookie not present

[]

I have read similar threads but none of it worked.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongmu3187 2019-07-12 17:51
    已采纳

    It appears that you are not using valid cookie name. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie

    It mentions =>

    A cookie-name can be any US-ASCII characters except control characters (CTLs), spaces, or tabs. It also must not contain a separator character like the following: ( ) < > @ , ; : \ " / [ ] ? = { }.

    if you use cookie name as just Name: "SpiderMan" it should work.

    点赞 评论
  • douzen1896 2019-07-12 18:09

    The problem you are having is caused by the name of your cookie. Adjust the names to not have whitespace and they will work as expected.

    Example:

    c2 := http.Cookie{Name: "Kabir-Singh", Value: "BollyWood", Path: "/", Expires: expiration, Secure: false}
    
    http.SetCookie(w, &c2)
    
    点赞 评论

相关推荐 更多相似问题