config.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package mhayaProfile
  2. import (
  3. "time"
  4. jsoniter "github.com/json-iterator/go"
  5. cfacade "github.com/mhaya/facade"
  6. )
  7. type (
  8. Config struct {
  9. jsoniter.Any
  10. }
  11. )
  12. func Wrap(val interface{}) *Config {
  13. return &Config{
  14. Any: jsoniter.Wrap(val),
  15. }
  16. }
  17. func (p *Config) GetConfig(path ...interface{}) cfacade.ProfileJSON {
  18. return &Config{
  19. Any: p.Any.Get(path...),
  20. }
  21. }
  22. func (p *Config) GetString(path interface{}, defaultVal ...string) string {
  23. result := p.Get(path)
  24. if result.LastError() != nil {
  25. if len(defaultVal) > 0 {
  26. return defaultVal[0]
  27. }
  28. return ""
  29. }
  30. return result.ToString()
  31. }
  32. func (p *Config) GetBool(path interface{}, defaultVal ...bool) bool {
  33. result := p.Get(path)
  34. if result.LastError() != nil {
  35. if len(defaultVal) > 0 {
  36. return defaultVal[0]
  37. }
  38. return false
  39. }
  40. return result.ToBool()
  41. }
  42. func (p *Config) GetInt(path interface{}, defaultVal ...int) int {
  43. result := p.Get(path)
  44. if result.LastError() != nil {
  45. if len(defaultVal) > 0 {
  46. return defaultVal[0]
  47. }
  48. return 0
  49. }
  50. return result.ToInt()
  51. }
  52. func (p *Config) GetInt32(path interface{}, defaultVal ...int32) int32 {
  53. result := p.Get(path)
  54. if result.LastError() != nil {
  55. if len(defaultVal) > 0 {
  56. return defaultVal[0]
  57. }
  58. return 0
  59. }
  60. return result.ToInt32()
  61. }
  62. func (p *Config) GetInt64(path interface{}, defaultVal ...int64) int64 {
  63. result := p.Get(path)
  64. if result.LastError() != nil {
  65. if len(defaultVal) > 0 {
  66. return defaultVal[0]
  67. }
  68. return 0
  69. }
  70. return result.ToInt64()
  71. }
  72. func (p *Config) GetDuration(path interface{}, defaultVal ...time.Duration) time.Duration {
  73. result := p.Get(path)
  74. if result.LastError() != nil {
  75. if len(defaultVal) > 0 {
  76. return defaultVal[0]
  77. }
  78. return 0
  79. }
  80. return time.Duration(result.ToInt64())
  81. }
  82. func (p *Config) Unmarshal(value interface{}) error {
  83. if p.LastError() != nil {
  84. return p.LastError()
  85. }
  86. return jsoniter.UnmarshalFromString(p.ToString(), value)
  87. }