Gorilla使用包装器会话cookie使用

时间:2018-01-24 21:37:55

标签: go gorilla

我在这样的Web应用程序中使用基本包装器:

package main

import (
    "fmt"
    "log"
    "net/http"
    "os"

    "github.com/gorilla/mux"
    "github.com/gorilla/sessions"
)

const (
    PORT = "8083"
)

func navbarWrapper(h http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "header")
        h(w, r) // call original function
        fmt.Fprintln(w, "footer")
    }
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/cookie_write", navbarWrapper(cookie_write))

    hostname, _ := os.Hostname()
    log.Printf("Listening on port %s https://%s:%s/", PORT, hostname, PORT)
    http.ListenAndServe(":"+PORT, r)
}

我想设置一个cookie,但它没有被发送到浏览器,但也没有提供错误

var (
    key   = []byte("16bytestufffffff")
    store = sessions.NewCookieStore(key)
)

func cookie_write(w http.ResponseWriter, r *http.Request) {
    session, _ := store.Get(r, "session-name")

    session.Values["authenticated"] = true
    session.Values["stuff"] = "important info"
    if err := session.Save(r, w); err != nil {
        fmt.Println(err)
        fmt.Println("error")
    } else {
        fmt.Println("worked?")
    }
}

如果我删除包装器,那么它工作正常,我可以看到在浏览器中生成的cookie:

r.HandleFunc("/cookie_write", cookie_write)

我知道我不能正确保存会话,但我无法弄明白该怎么做。

0 个答案:

没有答案