Home | Back


ทดสอบการใช้ Cookie Session ใน Negroni

Friday, 17 July 2015



การใช้ Cookie ในเวบแอป เป็นเรื่องที่ปกติมาก ๆ และใช้บ่อย ๆ เลยอยากเขียนตัวอย่างการใช้งาน Cookie Session แบบง่าย ๆ ที่ใช้ร่วมกับ Negroni ดังนี้ครับ

File : web.go

package main

import (
  "fmt"
  "runtime"
  "net/http"
  "github.com/goincremental/negroni-sessions"
  "github.com/goincremental/negroni-sessions/cookiestore"
  "github.com/codegangsta/negroni"
  "github.com/gorilla/mux"
)

func setData(w http.ResponseWriter, req *http.Request) {
  vars := mux.Vars(req)
  sess := sessions.GetSession(req)
  sess.Set(vars["name"], vars["data"])
  fmt.Fprintf(w, "Set %s to %s", vars["name"], vars["data"])
}

func getData(w http.ResponseWriter, req *http.Request) {
  vars := mux.Vars(req)
  sess := sessions.GetSession(req)
  data := sess.Get(vars["name"])
  switch data.(type) {
    case string: fmt.Fprintf(w, "Get %s is %s", vars["name"], data.(string))
    default: fmt.Fprintf(w, "Cannot get %s", vars["name"])
  }
}

func main() {
  runtime.GOMAXPROCS(4)
  r := mux.NewRouter()

  r.HandleFunc("/set/{name}/{data}", setData)
  r.HandleFunc("/get/{name}", getData)

  store := cookiestore.New([]byte("This is very secret key"))

  store.Options(sessions.Options{
    Path:  "/",
    Domain: "",
    MaxAge: 10,
    Secure: false,
    HTTPOnly: false,
  })

  n := negroni.New(negroni.NewRecovery(), negroni.NewStatic(http.Dir("public")))
  n.Use(sessions.Sessions("MyApp", store))
  n.UseHandler(r)
  n.Run(":8400")
}

หลังจาก compile แล้วก็ทดลองเล่นกันได้เลยค้าฟฟฟ



Home | Back