Skip to content

Instantly share code, notes, and snippets.

@andreadipersio
Created November 15, 2013 19:07
Show Gist options
  • Select an option

  • Save andreadipersio/7489843 to your computer and use it in GitHub Desktop.

Select an option

Save andreadipersio/7489843 to your computer and use it in GitHub Desktop.

Revisions

  1. andreadipersio created this gist Nov 15, 2013.
    61 changes: 61 additions & 0 deletions securecookie-example.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,61 @@
    package main

    import (
    "fmt"
    "log"

    "flag"

    "net/http"

    "github.com/andreadipersio/securecookie"
    )

    const (
    secret = "ii!^avQiOkv)QXhQwQZ>JH!YY/q(v%hY"
    )

    var (
    port int
    )

    func authHandler(w http.ResponseWriter, r *http.Request) {
    // http://golang.org/pkg/net/http/#Cookie
    cookie := &http.Cookie {
    Name: "token",
    Value: "foobar",
    }

    securecookie.SetSecureCookie(w, secret, cookie)
    }

    func rootHandler(w http.ResponseWriter, r *http.Request) {
    c, err := securecookie.GetSecureCookie(r, secret, "token")

    if err != nil || c.Value != "foobar" {
    http.Error(w, "You shall not pass", 401)
    return
    }

    fmt.Fprintf(w, "Access granted")
    }

    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 check cookie
    http.HandleFunc("/", rootHandler)

    log.Fatal(http.ListenAndServe(httpAddr, nil))
    }