-
Notifications
You must be signed in to change notification settings - Fork 67
/
tenant.go
54 lines (41 loc) 路 1.05 KB
/
tenant.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 middleware
import (
"context"
"fmt"
"net/http"
"github.com/google/uuid"
)
type key string
var (
TenantIDKey key = "tenantID"
)
const HeaderTenantID = "X-Tracetest-TenantID"
func TenantMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
tenantID := getTenantIDFromRequest(r)
// if tenant id exists and is invalid we return a 400 error
if tenantID != "" && !isValidUUID(tenantID) {
err := fmt.Errorf("invalid tenant id: %s", tenantID)
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
ctx = context.WithValue(ctx, TenantIDKey, tenantID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func getTenantIDFromRequest(r *http.Request) string {
return r.Header.Get(HeaderTenantID)
}
func isValidUUID(value string) bool {
_, err := uuid.Parse(value)
return err == nil
}
func TenantIDFromContext(ctx context.Context) string {
tenantID := ctx.Value(TenantIDKey)
if tenantID == nil {
return ""
}
return tenantID.(string)
}