-
Notifications
You must be signed in to change notification settings - Fork 59
/
policy.go
99 lines (83 loc) · 2.36 KB
/
policy.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
98
99
package config
import (
"encoding/json"
"errors"
"fmt"
"golang.ngrok.com/ngrok/internal/pb"
po "golang.ngrok.com/ngrok/policy"
)
type policy po.Policy
type rule po.Rule
type action po.Action
// WithPolicyString configures this edge with the provided policy configuration
// passed as a json string and overwrites any previously-set traffic policy
// https://ngrok.com/docs/http/traffic-policy
func WithPolicyString(jsonStr string) interface {
HTTPEndpointOption
TLSEndpointOption
TCPEndpointOption
} {
p := &policy{}
if err := json.Unmarshal([]byte(jsonStr), p); err != nil {
panic("invalid json for policy configuration")
}
return p
}
// WithPolicy configures this edge with the given traffic policy and overwrites any
// previously-set traffic policy
// https://ngrok.com/docs/http/traffic-policy/
func WithPolicy(p po.Policy) interface {
HTTPEndpointOption
TLSEndpointOption
TCPEndpointOption
} {
ret := policy(p)
return &ret
}
func (p *policy) ApplyTLS(opts *tlsOptions) {
opts.Policy = p
}
func (p *policy) ApplyHTTP(opts *httpOptions) {
opts.Policy = p
}
func (p *policy) ApplyTCP(opts *tcpOptions) {
opts.Policy = p
}
func (p *policy) toProtoConfig() *pb.MiddlewareConfiguration_Policy {
if p == nil {
return nil
}
inbound := make([]*pb.MiddlewareConfiguration_PolicyRule, len(p.Inbound))
for i, inP := range p.Inbound {
inbound[i] = rule(inP).toProtoConfig()
}
outbound := make([]*pb.MiddlewareConfiguration_PolicyRule, len(p.Outbound))
for i, outP := range p.Outbound {
outbound[i] = rule(outP).toProtoConfig()
}
return &pb.MiddlewareConfiguration_Policy{
Inbound: inbound,
Outbound: outbound,
}
}
func (pr rule) toProtoConfig() *pb.MiddlewareConfiguration_PolicyRule {
actions := make([]*pb.MiddlewareConfiguration_PolicyAction, len(pr.Actions))
for i, act := range pr.Actions {
actions[i] = action(act).toProtoConfig()
}
return &pb.MiddlewareConfiguration_PolicyRule{Name: pr.Name, Expressions: pr.Expressions, Actions: actions}
}
func (a action) toProtoConfig() *pb.MiddlewareConfiguration_PolicyAction {
var cfgBytes []byte = nil
if len(a.Config) > 0 {
var err error
cfgBytes, err = json.Marshal(a.Config)
if err != nil {
panic(errors.New(fmt.Sprintf("failed to parse action configuration due to error: %s", err.Error())))
}
}
return &pb.MiddlewareConfiguration_PolicyAction{
Type: a.Type,
Config: cfgBytes,
}
}