quartzgun/cookie/cookie.go

38 lines
741 B
Go

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, ttl int) {
cookie := http.Cookie{
Name: field,
Value: token,
Expires: time.Now().Add(time.Duration(ttl) * time.Minute),
}
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
}
}