conf.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. // Copyright 2021 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package conf
  15. import (
  16. "bytes"
  17. "encoding/json"
  18. "fmt"
  19. "gopkg.in/yaml.v3"
  20. "io"
  21. "io/ioutil"
  22. "net/http"
  23. "os"
  24. "path"
  25. "path/filepath"
  26. "runtime"
  27. "time"
  28. "github.com/sirupsen/logrus"
  29. )
  30. type (
  31. config struct {
  32. Port int `yaml:"port"`
  33. Timeout int `yaml:"timeout"`
  34. IntervalTime int `yaml:"intervalTime"`
  35. Ip string `yaml:"ip"`
  36. ConsoleLog bool `yaml:"consoleLog"`
  37. FileLog bool `yaml:"fileLog"`
  38. LogPath string `yaml:"logPath"`
  39. CommandDir string `yaml:"commandDir"`
  40. }
  41. )
  42. var gConf config
  43. func GetConf() *config {
  44. return &gConf
  45. }
  46. func (c *config) GetIntervalTime() int {
  47. return c.IntervalTime
  48. }
  49. func (c *config) GetIp() string {
  50. return c.Ip
  51. }
  52. func (c *config) GetPort() int {
  53. return c.Port
  54. }
  55. func (c *config) GetLogPath() string {
  56. return c.LogPath
  57. }
  58. func (c *config) GetCommandDir() string {
  59. return c.CommandDir
  60. }
  61. func processPath(path string) (string, error) {
  62. if abs, err := filepath.Abs(path); err != nil {
  63. return "", nil
  64. } else {
  65. if _, err := os.Stat(abs); os.IsNotExist(err) {
  66. return "", err
  67. }
  68. return abs, nil
  69. }
  70. }
  71. func (c *config) initConfig() bool {
  72. confPath, err := processPath(os.Args[1])
  73. if nil != err {
  74. fmt.Println("conf path err : ", err)
  75. return false
  76. }
  77. sliByte, err := ioutil.ReadFile(confPath)
  78. if nil != err {
  79. fmt.Println("load conf err : ", err)
  80. return false
  81. }
  82. err = yaml.Unmarshal(sliByte, c)
  83. if nil != err {
  84. fmt.Println("unmashal conf err : ", err)
  85. return false
  86. }
  87. if c.CommandDir, err = filepath.Abs(c.CommandDir); err != nil {
  88. fmt.Println("command dir err : ", err)
  89. return false
  90. }
  91. if _, err = os.Stat(c.CommandDir); os.IsNotExist(err) {
  92. fmt.Println("not found dir : ", c.CommandDir)
  93. return false
  94. }
  95. if c.LogPath, err = filepath.Abs(c.LogPath); nil != err {
  96. fmt.Println("log dir err : ", err)
  97. return false
  98. }
  99. if _, err = os.Stat(c.LogPath); os.IsNotExist(err) {
  100. if err = os.MkdirAll(path.Dir(c.LogPath), 0755); nil != err {
  101. fmt.Println("mak logdir err : ", err)
  102. return false
  103. }
  104. }
  105. return true
  106. }
  107. var (
  108. Log *logrus.Logger
  109. gClient http.Client
  110. )
  111. func (c *config) initTimeout() {
  112. gClient.Timeout = time.Duration(c.Timeout) * time.Millisecond
  113. }
  114. func (c *config) initLog() bool {
  115. Log = logrus.New()
  116. Log.SetReportCaller(true)
  117. Log.SetFormatter(&logrus.TextFormatter{
  118. CallerPrettyfier: func(f *runtime.Frame) (string, string) {
  119. filename := path.Base(f.File)
  120. return "", fmt.Sprintf("%s:%d", filename, f.Line)
  121. },
  122. DisableColors: true,
  123. FullTimestamp: true,
  124. })
  125. if c.FileLog {
  126. logFile, err := os.OpenFile(c.LogPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
  127. if err != nil {
  128. fmt.Println("Failed to init log file settings..." + err.Error())
  129. Log.Infof("Failed to log to file, using default stderr.")
  130. return false
  131. } else if c.ConsoleLog {
  132. mw := io.MultiWriter(os.Stdout, logFile)
  133. Log.SetOutput(mw)
  134. } else if !c.ConsoleLog {
  135. Log.SetOutput(logFile)
  136. }
  137. } else if c.ConsoleLog {
  138. Log.SetOutput(os.Stdout)
  139. }
  140. return true
  141. }
  142. func (c *config) Init() bool {
  143. if !c.initConfig() {
  144. return false
  145. }
  146. if !c.initLog() {
  147. return false
  148. }
  149. c.initTimeout()
  150. return true
  151. }
  152. func fetchContents(request *http.Request) (data []byte, err error) {
  153. respon, err := gClient.Do(request)
  154. if nil != err {
  155. return nil, err
  156. }
  157. defer respon.Body.Close()
  158. data, err = ioutil.ReadAll(respon.Body)
  159. if nil != err {
  160. return nil, err
  161. }
  162. /*
  163. if respon.StatusCode < 200 || respon.StatusCode > 299 {
  164. return data, fmt.Errorf("http return code: %d and error message %s.", respon.StatusCode, string(data))
  165. }
  166. */
  167. return data, err
  168. }
  169. func Get(inUrl string) (data []byte, err error) {
  170. request, err := http.NewRequest(http.MethodGet, inUrl, nil)
  171. if nil != err {
  172. return nil, err
  173. }
  174. return fetchContents(request)
  175. }
  176. func Post(inHead, inBody string) (data []byte, err error) {
  177. request, err := http.NewRequest(http.MethodPost, inHead, bytes.NewBuffer([]byte(inBody)))
  178. if nil != err {
  179. return nil, err
  180. }
  181. request.Header.Set("Content-Type", "application/json")
  182. return fetchContents(request)
  183. }
  184. func Put(inHead, inBody string) (data []byte, err error) {
  185. request, err := http.NewRequest(http.MethodPut, inHead, bytes.NewBuffer([]byte(inBody)))
  186. if nil != err {
  187. return nil, err
  188. }
  189. request.Header.Set("Content-Type", "application/json")
  190. return fetchContents(request)
  191. }
  192. func Delete(inUrl string) (data []byte, err error) {
  193. request, err := http.NewRequest(http.MethodDelete, inUrl, nil)
  194. if nil != err {
  195. return nil, err
  196. }
  197. return fetchContents(request)
  198. }
  199. func LoadFileUnmarshal(path string, ret interface{}) error {
  200. sliByte, err := ioutil.ReadFile(path)
  201. if nil != err {
  202. return err
  203. }
  204. err = json.Unmarshal(sliByte, ret)
  205. if nil != err {
  206. return err
  207. }
  208. return nil
  209. }
  210. func SaveFileMarshal(path string, content interface{}) error {
  211. data, err := json.Marshal(content)
  212. if nil != err {
  213. return err
  214. }
  215. return ioutil.WriteFile(path, data, 0666)
  216. }