当前位置: 首页 > 工具软件 > Gorilla > 使用案例 >

gorilla/securecookie /gorilla/sessions

孙才捷
2023-12-01
var store = sessions.NewCookieStore([]byte("something-very-secret"))

func MyHandler(w http.ResponseWriter, r *http.Request) {

    session, err := store.Get(r, "s1")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    fmt.Println(session)
    session.Values["name"] = "kingeastensun"
    session.Save(r, w)
}

func MultiSessionHandler(w http.ResponseWriter, r *http.Request) {
    session1, err := store.Get(r, "s1")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    fmt.Println(session1)
    session1.Values["name"] = "kingeastensun"

    session2, err := store.Get(r, "s2")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    fmt.Println(session2)
    session2.Values["name"] = "kingeastensunyx"
    sessions.Save(r, w)

}

var hashKey = []byte("1111111111111111")
var blockKey = []byte("1111111111111111")
var sc = securecookie.New(hashKey, blockKey)

// func init() {
//  codecs := securecookie.CodecsFromPairs(
//      []byte("new-hash-key"),
//      []byte("new-block-key"),
//      []byte("old-hash-key"),
//      []byte("old-block-key"),
//  )

//  for _, code := range codecs {
//      if cookie, ok := code.(*securecookie.SecureCookie); ok == true {
//          cookie.MaxAge(86400 * 7)
//          cookie.SetSerializer(securecookie.JSONEncoder{})
//          cookie.HashFunc(sha512.New512_256)
//      }
//  }
// }

func SetCookieHandler(w http.ResponseWriter, r *http.Request) {
    value := map[string]string{
        "name": "kingeasternsun",
    }
    if svalue, err := sc.Encode("kes", &value); err == nil {
        ck := &http.Cookie{
            Name:  "kes",
            Value: svalue,
        }
        http.SetCookie(w, ck)
    } else {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
}

func GetCookieHandler(w http.ResponseWriter, r *http.Request) {
    if cValue, err := r.Cookie("kes"); err == nil {
        value := make(map[string]string)
        if err = sc.Decode("kes", cValue.Value, &value); err == nil {
            fmt.Fprintf(w, "The value of n ame is %q", value["name"])
        }
    }

}

func main() {
    // fmt.Println(string(securecookie.GenerateRandomKey(32)))
    // fmt.Println(string(securecookie.GenerateRandomKey(32)))
    routes := mux.NewRouter()
    routes.HandleFunc("/session", MyHandler)
    routes.HandleFunc("/musession", MultiSessionHandler)
    routes.HandleFunc("/setcookie", SetCookieHandler)
    routes.HandleFunc("/getcookie", GetCookieHandler)

    http.Handle("/", routes)
    http.ListenAndServe(":8080", nil)
}
 类似资料: