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

无法在标题中设置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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用verilog实现tanh函数和softplus函数
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题