/
app.go
272 lines (248 loc) · 7.32 KB
/
app.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
package consul
import (
"fmt"
"io/ioutil"
"log"
"net/url"
"os"
"os/signal"
"reflect"
"strings"
"github.com/chennqqi/goutils/closeevent"
"github.com/chennqqi/goutils/utils"
"github.com/chennqqi/goutils/yamlconfig"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
)
type ConsulApp struct {
*ConsulOperator
}
// load an conf file text form file(FQDN)
// try consul first, if not exist, try local file
func ReadTxt(c *ConsulOperator, file string) ([]byte, error) {
if strings.HasPrefix(file, "consul://") {
u, err := url.Parse(file)
if c == nil {
return nil, errors.New("consul not set")
} else if err != nil {
return nil, err
} else {
return c.Get(u.Path)
}
} else {
return ioutil.ReadFile(file)
}
}
// create a consul app with load cfg, using 127.0.0.1:8500
// cfg is required parameter, the cfg address
// arg heathHost is must parameter, a health http address of app
// arg consulUrl is an FQDN format string which contains consul host,port,configpath
func NewAppWithCustomCfg(cfg interface{}, confName, healthHost string) (*ConsulApp, error) {
var capp ConsulApp
appName := utils.ApplicationName()
consulapi := NewConsulOp("")
consulapi.Fix()
capp.ConsulOperator = consulapi
if err := consulapi.Ping(); err != nil {
if confName == "" {
confName = fmt.Sprintf("%s.yml", appName)
}
log.Println("[consul/app.go] ping consul failed, try local")
err := yamlconfig.Load(cfg, confName)
if os.IsNotExist(err) {
fmt.Println("configure not exist, make default")
yamlconfig.Save(cfg, confName)
return nil, err
} else if err != nil {
log.Printf("[consul/app.go] Load %v config from local error: %v", confName, err)
return nil, err
}
} else {
if confName == "" {
confName = fmt.Sprintf("config/%s.yml", appName)
} else if !strings.HasPrefix(confName, `config/`) {
confName = fmt.Sprintf("config/%s", confName)
}
txt, err := consulapi.Get(confName)
if err == nil {
yaml.Unmarshal(txt, cfg)
} else {
log.Printf("[consul/app.go] Load conf(%v) from consul error: %v", confName, err)
err = yamlconfig.Load(cfg, confName)
if err != nil {
fmt.Println("make empty local config")
yamlconfig.Save(cfg, confName)
return nil, errors.New("make empty local config")
}
}
}
//post fix consul
if healthHost == "" && cfg != nil {
st := reflect.ValueOf(cfg).Elem()
field := st.FieldByName("HealthHost")
if !field.IsValid() {
return nil, errors.New("cfg not contains`HealthHost")
}
healthHost = field.String()
}
if healthHost == "" {
return nil, errors.New("cfg or HealthHost must be valid")
}
{
consulapi.Name = appName
v := strings.Split(healthHost, ":")
if len(v) > 1 {
fmt.Sscanf(v[1], "%d", &consulapi.Port)
}
}
return &capp, nil
}
// create a consul app with load cfg, using 127.0.0.1:8500
// cfg is required parameter, the cfg address
// arg heathHost is must parameter, a health http address of app
// arg consulUrl is an FQDN format string which contains consul host,port,configpath, if configpath is empty,
// ${appname}.yml, config/${appname} will be tried to load in order
func NewAppWithCfgEx(cfg interface{}, healthHost, consulUrl string) (*ConsulApp, error) {
var capp ConsulApp
appinfo, err := ParseConsulUrl(consulUrl)
if err != nil {
return nil, err
}
appName := utils.ApplicationName()
consulapi := NewConsulOp(consulUrl)
consulapi.Fix()
capp.ConsulOperator = consulapi
//try /${APPNAME}.yml
//try /config/${APPNAME}.yml
//try /config/${APPNAME}.yml
var names []string
var defaultName string
var confName = appinfo.Config
if confName == "" {
confName = fmt.Sprintf("%s.yml", appName)
defaultName = confName
names = append(names, confName)
confName = appName
names = append(names, confName)
confName = fmt.Sprintf("config/%s.yml", appName)
names = append(names, confName)
confName = fmt.Sprintf("config/%s", confName)
names = append(names, confName)
} else {
names = append(names, confName)
defaultName = appinfo.Config
}
if err := consulapi.Ping(); err != nil {
log.Println("[consul/app.go] ping consul failed, try local")
var exist bool
for i := 0; i < len(names); i++ {
log.Printf("[consul/app.go] ping consul failed, try load %v", names[i])
err := yamlconfig.Load(cfg, names[i])
if err == nil {
exist = true
break
}
}
if !exist {
log.Printf("[consul/app.go] all try load failed, make default %v", defaultName)
yamlconfig.Save(cfg, defaultName)
return nil, ErrNotExist
}
} else { // consul is OK
//try /config/${APPNAME}.yml
var exist bool
for i := 0; i < len(names); i++ {
log.Printf("[consul/app.go] get consul kv: %v", names[i])
txt, err := consulapi.Get(names[i])
if err == nil {
yaml.Unmarshal(txt, cfg)
exist = true
break
}
}
if !exist {
log.Printf("[consul/app.go] all try load failed, make default %v", defaultName)
yamlconfig.Save(cfg, defaultName)
return nil, ErrNotExist
}
}
//post fix consul
if healthHost == "" && cfg != nil {
st := reflect.ValueOf(cfg).Elem()
field := st.FieldByName("HealthHost")
if !field.IsValid() {
field := st.FieldByName("Health")
if !field.IsValid() {
return nil, errors.New("cfg not contains`HealthHost or Health")
} else {
//should call url.Parse use ParseConsulUrl instand
healthHost = field.String()
}
} else {
healthHost = field.String()
}
}
if healthHost == "" {
return nil, errors.New("cfg.Health or cfg.HealthHost or HealthHost must be valid")
}
{
consulapi.Name = appName
v := strings.Split(healthHost, ":")
if len(v) > 1 {
fmt.Sscanf(v[1], "%d", &consulapi.Port)
}
}
return &capp, nil
}
// create a consul app with load cfg, using 127.0.0.1:8500
// cfg is required parameter, the cfg address
// arg heathHost is must parameter, a health http address of app
func NewAppWithCfg(cfg interface{}, healthHost string) (*ConsulApp, error) {
return NewAppWithCustomCfg(cfg, "", healthHost)
}
// create a consul app
// arg heathHost is must parameter, a health http address of app
// arg agent is option, if empty using default 127.0.0.1:8500
func NewApp(healthHost, agent string) (*ConsulApp, error) {
//post fix consul
if healthHost == "" {
return nil, errors.New("healHost must be valid")
}
if agent == "" {
agent = "127.0.0.1:8500"
}
var capp ConsulApp
appName := utils.ApplicationName()
consulapi := NewConsulOp(agent)
consulapi.Fix()
capp.ConsulOperator = consulapi
if err := consulapi.Ping(); err != nil {
log.Println("[main] ping consul failed, try local")
return nil, err
}
{
consulapi.Name = appName
v := strings.Split(healthHost, ":")
if len(v) > 1 {
fmt.Sscanf(v[1], "%d", &consulapi.Port)
}
}
return &capp, nil
}
// wait for main function return and register app to service to consul
func (c *ConsulApp) Wait(stopcall func(os.Signal), signals ...os.Signal) {
quitChan := make(chan os.Signal, 1)
defer close(quitChan)
if len(signals) > 0 {
signal.Notify(quitChan, signals...)
} else {
closeevent.CloseNotify(quitChan)
}
c.RegisterService()
sig := <-quitChan
log.Println("[main:main] quit, recv signal ", sig)
if stopcall != nil {
stopcall(sig)
}
c.DeregisterService()
}