-
Notifications
You must be signed in to change notification settings - Fork 0
/
extractors.go
43 lines (34 loc) · 1012 Bytes
/
extractors.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
package httputils
import (
"context"
"errors"
"net/http"
"strings"
"time"
"github.com/ecumenos/ecumenos/internal/toolkit/contextutils"
"github.com/ecumenos/ecumenos/internal/toolkit/random"
)
func ExtractRequestID(r *http.Request) string {
if reqID := r.Header.Get("X-Request-Id"); reqID != "" {
return reqID
}
return random.GenUUIDString()
}
func GetRequestDuration(ctx context.Context) (time.Duration, error) {
start, ok := contextutils.GetStartRequestTimestamp(ctx)
if !ok {
return 0, errors.New("start request wasn't set correctly")
}
return time.Since(start), nil
}
func ExtractJWTBearerToken(r *http.Request) (string, error) {
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
return "", errors.New("authorization header is missing")
}
authHeaderParts := strings.Split(authHeader, " ")
if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != "bearer" {
return "", errors.New("token prefix is missing")
}
return authHeaderParts[1], nil
}