dongou3158 2019-01-20 10:51
浏览 1563
已采纳

如何从golang中读取cookie?

I set a cookie from javascript such as :

setCookie("appointment", JSON.stringify({
                appointmentDate: selectedDay.date,
                appointmentStartMn: appointment.mnRange[0],
                appointmentId: appointment.id || 0,
                appointmentUserId: appointment.user.id || 0
          })
);

After cookie is set I want to redirect the user to a booking page :

window.location.href = "https://localhost:8080/booking/"

The setCookie function :

function setCookie(cookieName, cookieValue) {
    document.cookie = `${cookieName}=${cookieValue};secure;`;
}

I'd like to retrieve that cookie from my go backend but I can't figure out how to do this. I've read about this question since I've never used cookies before but the answers seems to tell that I don't have to do much aside from setting document.cookie.

In my browser storage I can see the cookie is indeed set as expected.

In my go backend I want to print the cookie :

r.HandleFunc("/booking/", handler.serveTemplate)

func (handler *templateHandler) serveTemplate(w http.ResponseWriter, r *http.Request) {
    c, err := r.Cookie("appointment")
    if err != nil {
        fmt.Println(err.Error())
    } else {
        fmt.Println(c.Value)
    }
}

//output http: named cookie not present

What is the specific I am missing ? I think I'm confusing local/http cookie but how to achieve the reading of client set cookies ?

UPDATE (see answer for more)

It has nothing to do with golang. My :

appointmentDate: selectedDay.date

What formatted as 2019-01-01 and - is not a valid character that can be send to the backend. It worked into my browser, but it needs to be URI encoded to be passed.

So this did the trick :

`${cookieName}=${encodeURIComponent(cookieValue)};secure;` + "path=/";`

And in go (didn't catch err here to save space) :

cookie, _ := r.Cookie("appointment")
data, _ := url.QueryUnescape(cookie.Value)
  • 写回答

1条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 ubuntu18.04 tty报错&tty界面su/sudo命令无法执行,如何解决?
      • ¥20 关于c语言网络编程,实现传文件和即时聊天
      • ¥20 下面的压缩方法是否可行
      • ¥15 结构体数组读取文件信息失败,读取不了
      • ¥15 kaldi thchs30 训练遇到问题
      • ¥15 shellter无法使用,如何解决?(操作系统-kali)
      • ¥15 matlab动态模态分解程序
      • ¥60 关于渗透及远控的几个问题
      • ¥15 python文本词汇出现次数统计
      • ¥15 使用按键和串口,记录按键在不消抖的情况下触发的次数