app.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package conf
  2. import (
  3. "fmt"
  4. "os"
  5. "box-cost/log"
  6. "github.com/spf13/viper"
  7. )
  8. type AppConf struct {
  9. Name string
  10. Version string
  11. Jwt struct {
  12. Realm string
  13. Key string
  14. TimeoutHour int
  15. }
  16. Redis struct {
  17. Addr string
  18. Password string // no password set
  19. Db int // use default DB
  20. }
  21. Log struct {
  22. FileName string
  23. Level int32
  24. ServiceName string
  25. }
  26. Port int32
  27. Mongo struct {
  28. DSN string
  29. Database string
  30. }
  31. Debug struct {
  32. UserId string
  33. UserPhone string
  34. UserRole string
  35. }
  36. Nats struct {
  37. Url string
  38. MaxReconnect int
  39. ReconnDelaySecond int
  40. }
  41. }
  42. func LoadConfFile(filepath string) (*AppConf, error) {
  43. file, err := os.Open(filepath)
  44. if err != nil {
  45. log.Errorf("can not open file:%s", filepath)
  46. return nil, err
  47. }
  48. v := viper.New()
  49. v.SetConfigType("yaml")
  50. err = v.ReadConfig(file)
  51. if err != nil {
  52. return nil, err
  53. }
  54. c := new(AppConf)
  55. err = v.Unmarshal(c)
  56. return c, err
  57. }
  58. func NewAppConf(filePath string) (*AppConf, error) {
  59. c, err := LoadConfFile(filePath)
  60. if err != nil {
  61. return c, err
  62. }
  63. //初始化log
  64. _ = log.NewLoggerSugar(c.Log.ServiceName, c.Log.FileName, c.Log.Level)
  65. natsHost := os.Getenv("NATS")
  66. if len(natsHost) > 0 {
  67. c.Nats.Url = natsHost
  68. }
  69. fmt.Println("Env NATS=>", natsHost)
  70. AppConfig = c
  71. return c, nil
  72. }
  73. var AppConfig *AppConf = nil