saved
This commit is contained in:
47
frontend/cookie/cookie.go
Normal file
47
frontend/cookie/cookie.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package cookie
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrValueTooLong = errors.New("cookie value too long")
|
||||
ErrInvalidValue = errors.New("invalid cookie value")
|
||||
)
|
||||
|
||||
func Write(w http.ResponseWriter, cookie http.Cookie) error {
|
||||
// Encode the cookie value using base64.
|
||||
cookie.Value = base64.URLEncoding.EncodeToString([]byte(cookie.Value))
|
||||
|
||||
// Check the total length of the cookie contents. Return the ErrValueTooLong
|
||||
// error if it's more than 4096 bytes.
|
||||
if len(cookie.String()) > 4096 {
|
||||
return ErrValueTooLong
|
||||
}
|
||||
|
||||
// Write the cookie as normal.
|
||||
http.SetCookie(w, &cookie)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func Read(r *http.Request, name string) (string, error) {
|
||||
// Read the cookie as normal.
|
||||
cookie, err := r.Cookie(name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Decode the base64-encoded cookie value. If the cookie didn't contain a
|
||||
// valid base64-encoded value, this operation will fail and we return an
|
||||
// ErrInvalidValue error.
|
||||
value, err := base64.URLEncoding.DecodeString(cookie.Value)
|
||||
if err != nil {
|
||||
return "", ErrInvalidValue
|
||||
}
|
||||
|
||||
// Return the decoded cookie value.
|
||||
return string(value), nil
|
||||
}
|
||||
Reference in New Issue
Block a user