Fragment Description:



Setting a Cookie with the 'http' package, only.
Another approach:
SecureCookie by Gorilla...
Package gorilla/securecookie encodes and decodes authenticated and optionally encrypted cookie values.
Secure cookies can't be forged, because their values are validated using HMAC.
When encrypted, the content is also inaccessible to malicious eyes.
See here:
http://www.gorillatoolkit.org/pkg/securecookie

httpSetGetCookie

Last update, on 2015, Fri 9 Oct, 16:15:39

/* ... <== see fragment description ... */

package main

import (
    "flag"
    "fmt"
    "log"
    "net/http"
)

var (
    port int
)

func init() {
    flag.IntVar(&port, "port", 8080, "HTTP Server Port")
    flag.Parse()
}
func main() {
    httpAddr := fmt.Sprintf(":%v", port)
    log.Printf("Listening to %v", httpAddr)
    // visit /auth to create a cookie
    http.HandleFunc("/auth", authHandler)
    // visit / to get the cookie value
    http.HandleFunc("/", cookieHandler)
    log.Fatal(http.ListenAndServe(httpAddr, nil))
}
func authHandler(w http.ResponseWriter, r *http.Request) {
    /*sign: type Cookie {      type Cookie struct {            Name  string
           Value string
           Path       string    // optional
           Domain     string    // optional
           Expires    time.Time // optional
           RawExpires string    // for reading cookies only
           // MaxAge=0 means no 'Max-Age' attribute specified.
           // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
           // MaxAge>0 means Max-Age attribute present and given in seconds
           MaxAge   int
           Secure   bool
           HttpOnly bool
           Raw      string
           Unparsed []string // Raw text of unparsed attribute-value pairs
       }
   */
    cookie := &http.Cookie{
        Name:  "token",
        Value: "foobar",
    }
    http.SetCookie(w, cookie)
}
func cookieHandler(w http.ResponseWriter, r *http.Request) {
    if c, err := r.Cookie("token"); err != nil || c.Value != "foobar" {
        http.Error(w, "Ah ah ah, you didn't say the magic word", 401)
        return
    }
    fmt.Fprintf(w, "Access granted")
}



Comments