nonce.go
38 lines1
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
package application
import (
"context"
"crypto/rand"
"encoding/base64"
"net/http"
)
type nonceKey struct{}
// NonceMiddleware generates a cryptographic nonce per request and stores it
// in the request context. Retrieve with NonceFromContext.
func NonceMiddleware() Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
nonce := generateNonce()
ctx := context.WithValue(r.Context(), nonceKey{}, nonce)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// NonceFromContext returns the per-request nonce, or empty string if none.
func NonceFromContext(ctx context.Context) string {
if v, ok := ctx.Value(nonceKey{}).(string); ok {
return v
}
return ""
}
func generateNonce() string {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
panic("crypto/rand failed: " + err.Error())
}
return base64.StdEncoding.EncodeToString(b)
}