File size: 1,513 Bytes
fea99b3 | 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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | package ffx
import (
"context"
"fmt"
)
type contextKey string
const (
accessContextKey contextKey = "access"
)
var ErrContextMissing = fmt.Errorf("access not found in context")
func SetAccessOnContext(ctx context.Context, access AccessConfig) context.Context {
return context.WithValue(ctx, accessContextKey, access)
}
func GetAccessFromContext(ctx context.Context) (AccessConfig, error) {
access, ok := ctx.Value(accessContextKey).(AccessConfig)
if !ok {
return nil, ErrContextMissing
}
if access == nil {
return nil, ErrContextMissing
}
return access, nil
}
type contextService struct{}
func (s *contextService) IsFeatureEnabled(ctx context.Context, feature Feature) (bool, error) {
access, err := GetAccessFromContext(ctx)
if err != nil {
return false, err
}
acc, ok := access[feature]
if !ok {
return false, fmt.Errorf("feature %s not found in access", feature)
}
return acc, nil
}
func NewContextService() Service {
return &contextService{}
}
type testContextService struct {
contextService Service
staticService Service
}
func (s *testContextService) IsFeatureEnabled(ctx context.Context, feature Feature) (bool, error) {
v, err := s.contextService.IsFeatureEnabled(ctx, feature)
if err == nil {
return v, nil
}
return s.staticService.IsFeatureEnabled(ctx, feature)
}
func NewTestContextService(defaultAccess AccessConfig) Service {
return &testContextService{
staticService: NewStaticService(defaultAccess),
contextService: NewContextService(),
}
}
|