json_conf.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // +build json
  2. package loader
  3. import (
  4. "encoding/json"
  5. "v2ray.com/core/common"
  6. "v2ray.com/core/common/log"
  7. )
  8. type NamedTypeMap map[string]string
  9. type JSONConfigLoader struct {
  10. cache NamedTypeMap
  11. idKey string
  12. configKey string
  13. }
  14. func NewJSONConfigLoader(cache NamedTypeMap, idKey string, configKey string) *JSONConfigLoader {
  15. return &JSONConfigLoader{
  16. idKey: idKey,
  17. configKey: configKey,
  18. cache: cache,
  19. }
  20. }
  21. func (this *JSONConfigLoader) LoadWithID(raw []byte, id string) (interface{}, error) {
  22. config, err := GetInstance(this.cache[id])
  23. if err != nil {
  24. return nil, err
  25. }
  26. if err := json.Unmarshal(raw, config); err != nil {
  27. return nil, err
  28. }
  29. return config, nil
  30. }
  31. func (this *JSONConfigLoader) Load(raw []byte) (interface{}, string, error) {
  32. var obj map[string]json.RawMessage
  33. if err := json.Unmarshal(raw, &obj); err != nil {
  34. return nil, "", err
  35. }
  36. rawID, found := obj[this.idKey]
  37. if !found {
  38. log.Error(this.idKey, " not found in JSON content.")
  39. return nil, "", common.ErrObjectNotFound
  40. }
  41. var id string
  42. if err := json.Unmarshal(rawID, &id); err != nil {
  43. return nil, "", err
  44. }
  45. rawConfig := json.RawMessage(raw)
  46. if len(this.configKey) > 0 {
  47. configValue, found := obj[this.configKey]
  48. if !found {
  49. log.Error(this.configKey, " not found in JSON content.")
  50. return nil, "", common.ErrObjectNotFound
  51. }
  52. rawConfig = configValue
  53. }
  54. config, err := this.LoadWithID([]byte(rawConfig), id)
  55. if err != nil {
  56. return nil, id, err
  57. }
  58. return config, id, nil
  59. }