/
package.go
100 lines (83 loc) · 2.44 KB
/
package.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
package service
import (
"net/url"
"time"
"github.com/dghubble/sling"
oHttp "github.com/fwtpe/owl-backend/common/http"
"github.com/fwtpe/owl-backend/common/http/client"
log "github.com/fwtpe/owl-backend/common/logruslog"
oConfig "github.com/fwtpe/owl-backend/common/model/config"
oSrv "github.com/fwtpe/owl-backend/common/service"
"github.com/h2non/gentleman/plugins/timeout"
"github.com/spf13/viper"
"gopkg.in/h2non/gentleman.v2"
)
var (
updateOnlyFlag bool
mysqlApiUrl string
logger = log.NewDefaultLogger("INFO")
MysqlApiService oSrv.MysqlApiService
ClientTimeout = 3 * time.Second
)
func InitPackage(vpConfig *viper.Viper) {
apiConfig := ToMysqlApiConfig(vpConfig)
SetMysqlApiUrl(apiConfig)
// Set a flag of heartbeat call
if vpConfig.GetString("hosts") != "" {
updateOnlyFlag = true
}
InitMysqlApiService(buildRestfulConfig(apiConfig))
}
func InitMysqlApiService(config *oHttp.RestfulClientConfig) {
MysqlApiService = oSrv.NewMysqlApiService(
&oSrv.MysqlApiServiceConfig{
config,
},
)
}
func ToMysqlApiConfig(config *viper.Viper) *oConfig.MysqlApiConfig {
return &oConfig.MysqlApiConfig{
Host: config.GetString("mysql_api.host"),
Resource: config.GetString("mysql_api.resource"),
}
}
func buildRestfulConfig(config *oConfig.MysqlApiConfig) *oHttp.RestfulClientConfig {
httpConfig := &client.HttpClientConfig{
Url: GetMysqlApiUrl(),
RequestTimeout: ClientTimeout,
}
return &oHttp.RestfulClientConfig{
HttpClientConfig: httpConfig,
FromModule: "hbs",
}
}
func SetMysqlApiUrl(cfg *oConfig.MysqlApiConfig) {
mysqlApiUrl = resolveUrl(cfg.Host, cfg.Resource)
logger.Infoln("[Config] MySQL_API=", mysqlApiUrl)
}
func GetMysqlApiUrl() string {
if mysqlApiUrl == "" {
logger.Errorln("[Config] Return empty MySQL_API_URL.")
}
return mysqlApiUrl
}
func NewSlingBase() *sling.Sling {
return sling.New().Base(GetMysqlApiUrl())
}
func NewMysqlApiCli() *gentleman.Client {
return gentleman.New().Use(timeout.Request(ClientTimeout)).URL(GetMysqlApiUrl())
}
func resolveUrl(host string, resource string) string {
if host == "" {
logger.Panicln("Empty host url of mysql_api.")
}
base, err := url.Parse(host)
if err != nil {
logger.Panicf("Cannot parse host of mysql_api: %s. Error: %v\n", host, err)
}
ref, err := url.Parse(resource)
if err != nil {
logger.Panicf("Cannot parse resource of mysql_api: %s. Error: %v\n", resource, err)
}
return base.ResolveReference(ref).String()
}