all repos — quartzgun @ 0e5a81f27b631f23afd06fef046176f4662792a3

lightweight web framework in go

cookie/cookie.go (raw)

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
package cookie

import (
	"crypto/rand"
	"net/http"
	"time"
)

var availableChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@!.#$_"

func GenToken(length int) string {
	ll := len(availableChars)
	b := make([]byte, length)
	rand.Read(b)
	for i := 0; i < length; i++ {
		b[i] = availableChars[int(b[i])%ll]
	}
	return string(b)
}

func StoreToken(field string, token string, w http.ResponseWriter, hrs int) {
	cookie := http.Cookie{
		Name:    field,
		Value:   token,
		Expires: time.Now().Add(time.Duration(hrs) * time.Hour),
	}

	http.SetCookie(w, &cookie)
}

func GetToken(field string, req *http.Request) (string, error) {
	c, err := req.Cookie(field)
	if err == nil {
		return c.Value, nil
	} else {
		return "", err
	}
}