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 }