-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathutils.go
54 lines (44 loc) · 1.18 KB
/
utils.go
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package csrf
import (
"crypto/rand"
"fmt"
"net/http"
"github.com/valyala/fasthttp"
"github.com/zerodha/fastglue"
)
const (
randomString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
)
// setCookie implements the cookie interface.
func setCookie(cookie *http.Cookie, w interface{}) error {
req, ok := w.(*fastglue.Request)
if !ok {
return fmt.Errorf("invalid param for w")
}
// Acquire cookie
fck := fasthttp.AcquireCookie()
defer fasthttp.ReleaseCookie(fck)
fck.SetKey(cookie.Name)
fck.SetValue(cookie.Value)
fck.SetMaxAge(cookie.MaxAge)
fck.SetPath(cookie.Path)
fck.SetSecure(cookie.Secure)
fck.SetHTTPOnly(cookie.HttpOnly)
fck.SetSameSite(fasthttp.CookieSameSite(cookie.SameSite))
fck.SetDomain(cookie.Domain)
fck.SetExpire(cookie.Expires)
req.RequestCtx.Response.Header.SetCookie(fck)
return nil
}
// generateRandomString generates a cryptographically random,
// alphanumeric string of length n.
func generateRandomString(n int) ([]byte, error) {
var bytes = make([]byte, n)
if _, err := rand.Read(bytes); err != nil {
return []byte{}, err
}
for k, v := range bytes {
bytes[k] = randomString[v%byte(len(randomString))]
}
return bytes, nil
}