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

如何从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)

图片转代码服务由CSDN问答提供 功能建议

我从javascript中设置了Cookie,例如:

  setCookie  (“约会”,JSON.stringify({
约会日期:selectedDay.date,
约会起始锰:约会。mnRange[0],
约会ID:约会ID || 0,
约会用户ID:约会。user.id|  | 0 
})
); 
   
 
 

设置cookie后,我要将用户重定向到预订页面:

  window.location.href =“ https:// localhost:8080 / booking /” 
   
 
 

setCookie函数: \ n

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

我想从go后端检索该cookie,但是我不知道该怎么做。 我已经读过有关此问题的信息,因为我以前从未使用过Cookie,但是答案似乎表明,除了设置document.cookie之外,我不需要做其他事情。

在我的 浏览器存储,我可以看到cookie确实按预期设置。

在我的后端,我想打印cookie:

  r  .HandleFunc(“ / booking /”,handler.serveTemplate)
 
func(handler * templateHandler)serveTemplate(w http.ResponseWriter,r * http.Request){
c,err:= r.Cookie(“约会”)  
 if err!= nil {
 fmt.Println(err.Error())
}否则{
 fmt.Println(c.Value)
} 
} 
 
 //输出http: 命名的cookie不存在
   
 
 

我缺少的具体内容是什么? 我认为我混淆了本地/ http cookie,但是如何实现读取客户端设置cookie?

UPDATE(请参阅答案以了解更多信息)

与golang无关。 我的:

 约会日期:selectedDay.date 
   
 
 

格式为 2019-01-01 < / code>和-不是可以发送到后端的有效字符。 它可以在我的浏览器中使用,但是需要经过URI编码才能传递。

所以这可以解决问题:

 `$  {cookieName} = $ {encodeURIComponent(cookieValue)};安全;`+“ path = /”;`
   
 
 

然后继续(在这里找不到错误) 以节省空间):

  cookie,_:= r.Cookie(“约会”)
data,_:= url.QueryUnescape(cookie.Value)
   
 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongtiao2105 2019-01-20 12:12
    已采纳

    A better way would be to encode your json into base64 for example. I made a working example...

    main.go

    package main
    
    import (
        "encoding/base64"
        "encoding/json"
        "fmt"
        "io"
        "io/ioutil"
        "net/http"
    )
    
    // Contains everything about an appointment
    type Appointment struct {
        Date    string `json:"appointmentDate"`    // Contains date as string
        StartMn string `json:"appointmentStartMn"` // Our startMn ?
        ID      int    `json:"appointmentId"`      // AppointmentId
        UserID  int    `json:"appointmentUserId"`  // UserId
    }
    
    func main() {
        handler := http.NewServeMux()
    
        // Main request
        handler.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
            fmt.Printf("Requested /
    ")
    
            // set typical headers
            w.Header().Set("Content-Type", "text/html")
            w.WriteHeader(http.StatusOK)
    
            // Read file
            b, _ := ioutil.ReadFile("index.html")
            io.WriteString(w, string(b))
        })
    
        // booking request
        handler.HandleFunc("/booking/", func(w http.ResponseWriter, r *http.Request) {
            fmt.Printf("Requested /booking/
    ")
    
            // set typical headers
            w.Header().Set("Content-Type", "text/html")
            w.WriteHeader(http.StatusOK)
    
            // Read cookie
            cookie, err := r.Cookie("appointment")
            if err != nil {
                fmt.Printf("Cant find cookie :/
    ")
                return
            }
    
            fmt.Printf("%s=%s
    ", cookie.Name, cookie.Value)
    
            // Cookie data
            data, err := base64.StdEncoding.DecodeString(cookie.Value)
            if err != nil {
                fmt.Printf("Error:", err)
            }
    
            var appointment Appointment
            er := json.Unmarshal(data, &appointment)
            if err != nil {
                fmt.Printf("Error: ", er)
            }
    
            fmt.Printf("%s, %s, %d, %d
    ", appointment.Date, appointment.StartMn, appointment.ID, appointment.UserID)
    
            // Read file
            b, _ := ioutil.ReadFile("booking.html")
            io.WriteString(w, string(b))
        })
    
        // Serve :)
        http.ListenAndServe(":8080", handler)
    }
    
    

    index.html

    <html>
        <head>
            <title>Your page</title>
        </head>
    <body>
        Setting cookie via Javascript
    
        <script type="text/javascript">
        window.onload = () => {
            function setCookie(name, value, days) {
                var expires = "";
                if (days) {
                    var date = new Date();
                    date.setTime(date.getTime() + (days*24*60*60*1000));
                    expires = "; expires=" + date.toUTCString();
                }
                document.cookie = name + "=" + btoa((value || ""))  + expires + "; path=/";
            }
    
            setCookie("appointment", JSON.stringify({
                        appointmentDate: "20-01-2019 13:06",
                        appointmentStartMn: "1-2",
                        appointmentId: 2,
                        appointmentUserId: 3
                })
            );
    
            document.location = "/booking/";
        }
        </script>
    </body>
    

    booking.html

    <html>
        <head>
            <title>Your page</title>
        </head>
    <body>
        Your booking is okay :)
    </body>
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题