forked from vmkteam/zenrpc-middleware
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxrequestid.go
More file actions
35 lines (27 loc) · 839 Bytes
/
xrequestid.go
File metadata and controls
35 lines (27 loc) · 839 Bytes
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
package middleware
import (
"context"
"crypto/rand"
"fmt"
"regexp"
"github.com/labstack/echo/v4"
)
const ctxXRequestIDKey = echo.HeaderXRequestID
var xRequestIDre = regexp.MustCompile(`[a-zA-Z0-9-]+`)
func generateXRequestID() string {
b := make([]byte, 16)
rand.Read(b)
return fmt.Sprintf("%x", b)
}
func isValidXRequestID(requestId string) bool {
return requestId != "" && len(requestId) <= 32 && xRequestIDre.Match([]byte(requestId))
}
// XRequestIDFromContext returns X-Request-ID from context.
func XRequestIDFromContext(ctx context.Context) string {
r, _ := ctx.Value(ctxXRequestIDKey).(string)
return r
}
// NewXRequestIDContext creates new context with X-Request-ID.
func NewXRequestIDContext(ctx context.Context, requestId string) context.Context {
return context.WithValue(ctx, ctxXRequestIDKey, requestId)
}