forked from tufanbarisyildirim/gonginx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
upstream_server.go
86 lines (72 loc) · 2.23 KB
/
upstream_server.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
package gonginx
import (
"fmt"
"sort"
"strings"
)
//UpstreamServer represents `server` directive in `upstream{}` block
type UpstreamServer struct {
Address string
Flags []string
Parameters map[string]string
}
//GetName return directive name, Statement interface
func (uss *UpstreamServer) GetName() string {
return "server"
}
//GetBlock block of an upstream, basically nil
func (uss *UpstreamServer) GetBlock() IBlock {
return nil
}
//GetParameters block of an upstream, basically nil
func (uss *UpstreamServer) GetParameters() []string {
return uss.GetDirective().Parameters
}
//GetDirective get directive of the upstreamserver
func (uss *UpstreamServer) GetDirective() *Directive {
//First, generate a new directive from upstream server
directive := &Directive{
Name: "server",
Parameters: make([]string, 0),
Block: nil,
}
//address it the first parameter of an upstream directive
directive.Parameters = append(directive.Parameters, uss.Address)
//Iterations are random in golang maps https://blog.golang.org/maps#TOC_7.
//we sort keys in different slice and print them sorted.
//we always expect key=values parameters to be sorted by key
paramNames := make([]string, 0)
for k := range uss.Parameters {
paramNames = append(paramNames, k)
}
sort.Strings(paramNames)
//append named parameters first
for _, k := range paramNames {
directive.Parameters = append(directive.Parameters, fmt.Sprintf("%s=%s", k, uss.Parameters[k]))
}
//append flags to the end of the directive.
for _, flag := range uss.Flags {
directive.Parameters = append(directive.Parameters, flag)
}
return directive
}
//NewUpstreamServer creates an upstream server from a directive
func NewUpstreamServer(directive IDirective) *UpstreamServer {
uss := &UpstreamServer{
Flags: make([]string, 0),
Parameters: make(map[string]string, 0),
}
for i, parameter := range directive.GetParameters() {
if i == 0 { // alright, we asuume that firstone should be a server address
uss.Address = parameter
continue
}
if strings.Contains(parameter, "=") { //a parameter like weight=5
s := strings.SplitN(parameter, "=", 2)
uss.Parameters[s[0]] = s[1]
} else {
uss.Flags = append(uss.Flags, parameter)
}
}
return uss
}