39 lines
762 B
Go
39 lines
762 B
Go
|
package cookie
|
||
|
|
||
|
import (
|
||
|
"net/http"
|
||
|
"crypto/rand"
|
||
|
"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
|
||
|
}
|
||
|
}
|