1
0

json.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. // Copyright 2014 beego Author. All Rights Reserved.
  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 config
  15. import (
  16. "encoding/json"
  17. "errors"
  18. "fmt"
  19. "io/ioutil"
  20. "os"
  21. "strings"
  22. "sync"
  23. )
  24. // JSONConfig is a json config parser and implements Config interface.
  25. type JSONConfig struct {
  26. }
  27. // Parse returns a ConfigContainer with parsed json config map.
  28. func (js *JSONConfig) Parse(filename string) (Configer, error) {
  29. file, err := os.Open(filename)
  30. if err != nil {
  31. return nil, err
  32. }
  33. defer file.Close()
  34. content, err := ioutil.ReadAll(file)
  35. if err != nil {
  36. return nil, err
  37. }
  38. return js.ParseData(content)
  39. }
  40. // ParseData returns a ConfigContainer with json string
  41. func (js *JSONConfig) ParseData(data []byte) (Configer, error) {
  42. x := &JSONConfigContainer{
  43. data: make(map[string]interface{}),
  44. }
  45. err := json.Unmarshal(data, &x.data)
  46. if err != nil {
  47. var wrappingArray []interface{}
  48. err2 := json.Unmarshal(data, &wrappingArray)
  49. if err2 != nil {
  50. return nil, err
  51. }
  52. x.data["rootArray"] = wrappingArray
  53. }
  54. x.data = ExpandValueEnvForMap(x.data)
  55. return x, nil
  56. }
  57. // JSONConfigContainer A Config represents the json configuration.
  58. // Only when get value, support key as section:name type.
  59. type JSONConfigContainer struct {
  60. data map[string]interface{}
  61. sync.RWMutex
  62. }
  63. // Bool returns the boolean value for a given key.
  64. func (c *JSONConfigContainer) Bool(key string) (bool, error) {
  65. val := c.getData(key)
  66. if val != nil {
  67. return ParseBool(val)
  68. }
  69. return false, fmt.Errorf("not exist key: %q", key)
  70. }
  71. // DefaultBool return the bool value if has no error
  72. // otherwise return the defaultval
  73. func (c *JSONConfigContainer) DefaultBool(key string, defaultval bool) bool {
  74. if v, err := c.Bool(key); err == nil {
  75. return v
  76. }
  77. return defaultval
  78. }
  79. // Int returns the integer value for a given key.
  80. func (c *JSONConfigContainer) Int(key string) (int, error) {
  81. val := c.getData(key)
  82. if val != nil {
  83. if v, ok := val.(float64); ok {
  84. return int(v), nil
  85. }
  86. return 0, errors.New("not int value")
  87. }
  88. return 0, errors.New("not exist key:" + key)
  89. }
  90. // DefaultInt returns the integer value for a given key.
  91. // if err != nil return defaltval
  92. func (c *JSONConfigContainer) DefaultInt(key string, defaultval int) int {
  93. if v, err := c.Int(key); err == nil {
  94. return v
  95. }
  96. return defaultval
  97. }
  98. // Int64 returns the int64 value for a given key.
  99. func (c *JSONConfigContainer) Int64(key string) (int64, error) {
  100. val := c.getData(key)
  101. if val != nil {
  102. if v, ok := val.(float64); ok {
  103. return int64(v), nil
  104. }
  105. return 0, errors.New("not int64 value")
  106. }
  107. return 0, errors.New("not exist key:" + key)
  108. }
  109. // DefaultInt64 returns the int64 value for a given key.
  110. // if err != nil return defaltval
  111. func (c *JSONConfigContainer) DefaultInt64(key string, defaultval int64) int64 {
  112. if v, err := c.Int64(key); err == nil {
  113. return v
  114. }
  115. return defaultval
  116. }
  117. // Float returns the float value for a given key.
  118. func (c *JSONConfigContainer) Float(key string) (float64, error) {
  119. val := c.getData(key)
  120. if val != nil {
  121. if v, ok := val.(float64); ok {
  122. return v, nil
  123. }
  124. return 0.0, errors.New("not float64 value")
  125. }
  126. return 0.0, errors.New("not exist key:" + key)
  127. }
  128. // DefaultFloat returns the float64 value for a given key.
  129. // if err != nil return defaltval
  130. func (c *JSONConfigContainer) DefaultFloat(key string, defaultval float64) float64 {
  131. if v, err := c.Float(key); err == nil {
  132. return v
  133. }
  134. return defaultval
  135. }
  136. // String returns the string value for a given key.
  137. func (c *JSONConfigContainer) String(key string) string {
  138. val := c.getData(key)
  139. if val != nil {
  140. if v, ok := val.(string); ok {
  141. return v
  142. }
  143. }
  144. return ""
  145. }
  146. // DefaultString returns the string value for a given key.
  147. // if err != nil return defaltval
  148. func (c *JSONConfigContainer) DefaultString(key string, defaultval string) string {
  149. // TODO FIXME should not use "" to replace non existence
  150. if v := c.String(key); v != "" {
  151. return v
  152. }
  153. return defaultval
  154. }
  155. // Strings returns the []string value for a given key.
  156. func (c *JSONConfigContainer) Strings(key string) []string {
  157. stringVal := c.String(key)
  158. if stringVal == "" {
  159. return nil
  160. }
  161. return strings.Split(c.String(key), ";")
  162. }
  163. // DefaultStrings returns the []string value for a given key.
  164. // if err != nil return defaltval
  165. func (c *JSONConfigContainer) DefaultStrings(key string, defaultval []string) []string {
  166. if v := c.Strings(key); v != nil {
  167. return v
  168. }
  169. return defaultval
  170. }
  171. // GetSection returns map for the given section
  172. func (c *JSONConfigContainer) GetSection(section string) (map[string]string, error) {
  173. if v, ok := c.data[section]; ok {
  174. return v.(map[string]string), nil
  175. }
  176. return nil, errors.New("nonexist section " + section)
  177. }
  178. // SaveConfigFile save the config into file
  179. func (c *JSONConfigContainer) SaveConfigFile(filename string) (err error) {
  180. // Write configuration file by filename.
  181. f, err := os.Create(filename)
  182. if err != nil {
  183. return err
  184. }
  185. defer f.Close()
  186. b, err := json.MarshalIndent(c.data, "", " ")
  187. if err != nil {
  188. return err
  189. }
  190. _, err = f.Write(b)
  191. return err
  192. }
  193. // Set writes a new value for key.
  194. func (c *JSONConfigContainer) Set(key, val string) error {
  195. c.Lock()
  196. defer c.Unlock()
  197. c.data[key] = val
  198. return nil
  199. }
  200. // DIY returns the raw value by a given key.
  201. func (c *JSONConfigContainer) DIY(key string) (v interface{}, err error) {
  202. val := c.getData(key)
  203. if val != nil {
  204. return val, nil
  205. }
  206. return nil, errors.New("not exist key")
  207. }
  208. // section.key or key
  209. func (c *JSONConfigContainer) getData(key string) interface{} {
  210. if len(key) == 0 {
  211. return nil
  212. }
  213. c.RLock()
  214. defer c.RUnlock()
  215. sectionKeys := strings.Split(key, "::")
  216. if len(sectionKeys) >= 2 {
  217. curValue, ok := c.data[sectionKeys[0]]
  218. if !ok {
  219. return nil
  220. }
  221. for _, key := range sectionKeys[1:] {
  222. if v, ok := curValue.(map[string]interface{}); ok {
  223. if curValue, ok = v[key]; !ok {
  224. return nil
  225. }
  226. }
  227. }
  228. return curValue
  229. }
  230. if v, ok := c.data[key]; ok {
  231. return v
  232. }
  233. return nil
  234. }
  235. func init() {
  236. Register("json", &JSONConfig{})
  237. }