cookies - 如何在 Go 中检索 cookie?

标签 cookies go

我在以 tmpl.Execute 开头的行上收到 undefined: msg 错误。你应该如何在 Go 中检索 cookie?

func contact(w http.ResponseWriter, r *http.Request) {
    if r.Method == "POST" {
        r.ParseForm()
        for k, v := range r.Form {
            fmt.Println("k:", k, "v:", v)
        }
        http.SetCookie(w, &http.Cookie{Name: "msg", Value: "Thanks"})
        http.Redirect(w, r, "/contact/", http.StatusFound)
    }
    if msg, err := r.Cookie("msg"); err != nil {
        msg := ""
    }
    tmpl, _ := template.ParseFiles("templates/contact.tmpl")
    tmpl.Execute(w, map[string]string{"Msg": msg})
}

最佳答案

您应该在 if 之外声明 msg:

    func contact(w http.ResponseWriter, r *http.Request) {
        var msg *http.Cookie

        if r.Method == "POST" {
            r.ParseForm()
            for k, v := range r.Form {
                fmt.Println("k:", k, "v:", v)
            }
            http.SetCookie(w, &http.Cookie{Name: "msg", Value: "Thanks"})
            http.Redirect(w, r, "/contact/", http.StatusFound)
        }

        msg, err := r.Cookie("msg")
        if err != nil {
            // we can't assign string to *http.Cookie
            // msg = ""

            // so you can do
            // msg = &http.Cookie{}
        }

        tmpl, _ := template.ParseFiles("templates/contact.tmpl")
        tmpl.Execute(w, map[string]string{"Msg": msg.String()})
    }

关于cookies - 如何在 Go 中检索 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19988574/

相关文章:

go - "package _/home/vitaly: unrecognized import path "_/home/vitaly "(import path does not begin with hostname)"

javascript - 无法删除 _fbp Cookie

javascript - jQuery.parseJSON(); 的反向操作是什么?

javascript - 如何根据cookie值从页面中删除元素?

dictionary - Go中的 map 初始化

oop - Golang OOP 说明

PHP:Cookie域/子域控制

cookies - 如何使用--header选项通过围攻发送cookie?

戈朗 : How to install official Go fonts for Golang developement

ios - 在越狱的 iOS 上使用 ar 或 libtool 创建静态存档失败