Otfe/misc/cookie/cookie.go

32 lines
682 B
Go
Raw Permalink Normal View History

2022-02-23 12:07:09 +00:00
package cookie
import (
"errors"
"net/http"
"time"
"git.1248.nz/1248/Otfe/misc/b64"
)
func Create(w http.ResponseWriter, name string, value string) {
c := &http.Cookie{Name: name, Value: b64.Encode(value)}
http.SetCookie(w, c)
}
func Read(r *http.Request, name string) (string, error) {
c, err := r.Cookie(name)
if err != nil {
return "", errors.New("Cookie not found")
}
value, err := b64.Decode(c.Value)
if err != nil {
return "", errors.New("Failed to decode cookie")
}
return value, nil
}
func Delete(w http.ResponseWriter, name string) {
http.SetCookie(w, &http.Cookie{Name: name, MaxAge: -1, Expires: time.Unix(1, 0)})
}