-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoption.go
121 lines (102 loc) · 2.47 KB
/
option.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package zenziva
import (
"github.com/gojek/heimdall/v7"
"github.com/gojek/heimdall/v7/hystrix"
"net/http"
"strings"
"time"
)
const (
// DefaultTimeout sets the default timeout of the HTTP client.
DefaultTimeout = 30 * time.Second
// BaseURLV1 sets the base URL of the API version 1.
BaseURLV1 = "https://reguler.zenziva.net/apps/smsapi.php"
)
// FnOption is a function that sets the option.
type FnOption func(o *Option)
// WithBaseURL sets the base URL of the API.
func WithBaseURL(s string) FnOption {
return func(o *Option) {
o.BaseURL = s
}
}
// WithUserKey sets the user key.
func WithUserKey(s string) FnOption {
return func(o *Option) {
o.UserKey = s
}
}
// WithPasswordKey sets the password key.
func WithPasswordKey(s string) FnOption {
return func(o *Option) {
o.PasswordKey = s
}
}
// WithTimeout sets the timeout of the HTTP client.
func WithTimeout(t time.Duration) FnOption {
return func(o *Option) {
o.ConnectTimeout = t
}
}
// WithClient sets the HTTP client.
func WithClient(c heimdall.Doer) FnOption {
return func(o *Option) {
o.Client = c
}
}
// WithHystrixOptions sets the hystrix options.
func WithHystrixOptions(opts ...hystrix.Option) FnOption {
return func(o *Option) {
o.HystrixOptions = append(o.HystrixOptions, opts...)
}
}
// Option is a config for Zenziva.
type Option struct {
BaseURL string
UserKey string
PasswordKey string
ConnectTimeout time.Duration
Client heimdall.Doer
HystrixOptions []hystrix.Option
client *hystrix.Client
}
func (o *Option) Assign(opts ...FnOption) *Option {
for _, opt := range opts {
opt(o)
}
return o
}
// Validate validates the config variables to ensure smooth integration.
func (o *Option) Validate() (err error) {
if o.UserKey == "" {
err = ErrEmptyUserKey
return
}
if o.PasswordKey == "" {
err = ErrEmptyPasswordKey
}
return
}
// DefaultV1 sets the config default value for version 1.
func (o *Option) DefaultV1() *Option {
if o.BaseURL == "" {
o.BaseURL = BaseURLV1
}
o.BaseURL = strings.TrimRight(o.BaseURL, "/")
return o.defaultVal()
}
func (o *Option) defaultVal() *Option {
if o.ConnectTimeout < DefaultTimeout {
o.ConnectTimeout = DefaultTimeout
}
if o.Client == nil {
o.Client = http.DefaultClient
}
opts := append([]hystrix.Option{
hystrix.WithHTTPTimeout(o.ConnectTimeout),
hystrix.WithHystrixTimeout(o.ConnectTimeout),
hystrix.WithHTTPClient(o.Client),
}, o.HystrixOptions...)
o.client = hystrix.NewClient(opts...)
return o
}