-
Notifications
You must be signed in to change notification settings - Fork 2
/
config.go
97 lines (79 loc) · 1.89 KB
/
config.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
96
97
package main
import (
"encoding/json"
xds "github.com/cncf/xds/go/xds/type/v3"
"github.com/envoyproxy/envoy/contrib/golang/filters/http/source/go/pkg/api"
"github.com/envoyproxy/envoy/contrib/golang/filters/http/source/go/pkg/http"
"google.golang.org/protobuf/types/known/anypb"
)
func init() {
http.RegisterHttpFilterConfigFactory("basic-auth", configFactory)
http.RegisterHttpFilterConfigParser(&parser{})
}
type config struct {
users map[string]string
}
type rawConfig struct {
Users []User
}
type User struct {
Username string
Password string
}
type parser struct {
}
func (p *parser) Parse(any *anypb.Any) (interface{}, error) {
configStruct := &xds.TypedStruct{}
if err := any.UnmarshalTo(configStruct); err != nil {
return nil, err
}
v := configStruct.Value
conf := &config{}
rc := &rawConfig{}
data, err := v.MarshalJSON()
if err != nil {
return nil, err
}
err = json.Unmarshal(data, rc)
if err != nil {
return nil, err
}
conf.users = paresUser2Map(&rc.Users)
return conf, nil
}
func paresUser2Map(users *[]User) map[string]string {
userMap := make(map[string]string)
for _, user := range *users {
if user.Username == "" {
continue
}
userMap[user.Username] = user.Password
}
return userMap
}
func (p *parser) Merge(parent interface{}, child interface{}) interface{} {
parentConfig := parent.(*config)
childConfig := child.(*config)
newConfig := *parentConfig
if childConfig.users != nil {
mergeUserMap(newConfig.users, childConfig.users)
}
return &newConfig
}
func mergeUserMap(new, child map[string]string) {
for username, password := range child {
new[username] = password
}
}
func configFactory(c interface{}) api.StreamFilterFactory {
conf, ok := c.(*config)
if !ok {
panic("unexpected config type")
}
return func(callbacks api.FilterCallbackHandler) api.StreamFilter {
return &filter{
callbacks: callbacks,
config: conf,
}
}
}