~bigbes/core-go

ref: c912a96a0444be89f4b4ed6d994f827869759da2 core-go/feature/header.go -rw-r--r-- 1.0 KiB
c912a96a — Drew DeVault Revert "auth: ensure semantic errors are bubbled up to user properly" 9 months ago
                                                                                
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
package feature

import (
	"context"
	"net/http"
	"strings"
)

var featureCtxKey = &contextKey{"feature"}

type contextKey struct {
	name string
}

// Creates an HTTP middleware to process Accept-Features headers.
func Middleware() func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			header := r.Header.Get("Accept-Features")
			features := strings.Split(header, ",")

			ctx := context.WithValue(r.Context(),
				featureCtxKey, features)
			r = r.WithContext(ctx)
			next.ServeHTTP(w, r)
		})
	}
}

// Returns the list of enabled features on this context.
func ForContext(ctx context.Context) []string {
	raw, ok := ctx.Value(featureCtxKey).([]string)
	if !ok {
		return []string{}
	}
	return raw
}

// Returns true if the requested feature is enabled via the Accept-Features
// HTTP header
func Enabled(ctx context.Context, name string) bool {
	for _, feat := range ForContext(ctx) {
		if feat == name {
			return true
		}
	}
	return false
}