-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcookie.go
More file actions
61 lines (54 loc) · 1.28 KB
/
cookie.go
File metadata and controls
61 lines (54 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package main
import (
"fmt"
"log"
"net/http"
"os"
"github.com/meehow/securebytes"
)
const cookieName = "securebytes"
var sb = securebytes.New([]byte(os.Getenv("SECRET")), securebytes.ASN1Serializer{})
// Session is a struct which will be saved in a cookie
type Session struct {
UserID int
Name string
}
func main() {
http.HandleFunc("/", handler)
addr := "localhost:8080"
fmt.Printf("Listening on http://%s\n", addr)
log.Fatal(http.ListenAndServe(addr, nil))
}
func handler(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie(cookieName)
if err == nil {
// Cookie found, let's read it
var session Session
err = sb.DecryptBase64(cookie.Value, &session)
if err != nil {
fmt.Fprintf(w, "Decryption error: %v", err)
return
}
fmt.Fprintf(w, "Your session cookie: %#v has been encoded to %s",
session, cookie.Value)
return
}
// Cookie not found, create a new one
session := Session{
UserID: 1234567890,
Name: "meehow",
}
b64, err := sb.EncryptToBase64(session)
if err != nil {
fmt.Fprintf(w, "Encryption error: %v", err)
return
}
cookie = &http.Cookie{
Name: cookieName,
Value: b64,
Path: "/",
HttpOnly: true,
}
http.SetCookie(w, cookie)
fmt.Fprint(w, "The cookie has been set. You can refresh this page to read it.")
}