forked from growthbook/growthbook-golang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
feature.go
95 lines (88 loc) · 2.33 KB
/
feature.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package growthbook
import "encoding/json"
// FeatureValue is a wrapper around an arbitrary type representing the
// value of a feature. Features can return any kinds of values, so
// this is an alias for interface{}.
type FeatureValue interface{}
// Feature has a default value plus rules than can override the
// default.
type Feature struct {
DefaultValue FeatureValue `json:"defaultValue"`
Rules []*FeatureRule `json:"rules"`
}
// ParseFeature creates a single Feature value from raw JSON input.
func ParseFeature(data []byte) *Feature {
dict := make(map[string]interface{})
err := json.Unmarshal(data, &dict)
if err != nil {
logError("Failed parsing JSON input", "Feature")
return nil
}
return BuildFeature(dict)
}
// BuildFeature creates a Feature value from a generic JSON value.
func BuildFeature(val interface{}) *Feature {
feature := Feature{}
dict, ok := val.(map[string]interface{})
if !ok {
logError("Invalid JSON data type", "Feature")
return nil
}
defaultValue, ok := dict["defaultValue"]
if ok {
feature.DefaultValue = defaultValue
}
rules, ok := dict["rules"]
if ok {
var rulesArray []interface{}
if rules == nil {
rulesArray = []interface{}{}
} else {
rulesArray, ok = rules.([]interface{})
if !ok {
logError("Invalid JSON data type", "Feature")
return nil
}
}
feature.Rules = make([]*FeatureRule, len(rulesArray))
for i := range rulesArray {
rule := BuildFeatureRule(rulesArray[i])
if rule == nil {
return nil
}
feature.Rules[i] = rule
}
}
return &feature
}
// BuildFeatureValues creates a FeatureValue array from a generic JSON
// value.
func BuildFeatureValues(val interface{}) []FeatureValue {
vals, ok := val.([]interface{})
if !ok {
logError("Invalid JSON data type", "FeatureValue")
return nil
}
result := make([]FeatureValue, len(vals))
for i, v := range vals {
// FeatureValue is just an alias for interface{}.
result[i] = v
}
return result
}
// BuildFeatures creates a Feature array from a generic JSON value.
func BuildFeatures(v interface{}) map[string]*Feature {
dict, ok := v.(map[string]interface{})
if !ok {
logError("Invalid JSON data type", "Features")
return nil
}
result := make(map[string]*Feature, len(dict))
for k, v := range dict {
feature := BuildFeature(v)
if feature != nil {
result[k] = feature
}
}
return result
}