loader.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package conf
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "v2ray.com/core/common"
  6. "v2ray.com/core/common/log"
  7. )
  8. var (
  9. ErrUnknownConfigID = errors.New("Unknown config ID.")
  10. )
  11. type ConfigCreator func() interface{}
  12. type ConfigCreatorCache map[string]ConfigCreator
  13. func (this ConfigCreatorCache) RegisterCreator(id string, creator ConfigCreator) error {
  14. if _, found := this[id]; found {
  15. return common.ErrDuplicatedName
  16. }
  17. this[id] = creator
  18. return nil
  19. }
  20. func (this ConfigCreatorCache) CreateConfig(id string) (interface{}, error) {
  21. creator, found := this[id]
  22. if !found {
  23. return nil, ErrUnknownConfigID
  24. }
  25. return creator(), nil
  26. }
  27. type JSONConfigLoader struct {
  28. cache ConfigCreatorCache
  29. idKey string
  30. configKey string
  31. }
  32. func NewJSONConfigLoader(cache ConfigCreatorCache, idKey string, configKey string) *JSONConfigLoader {
  33. return &JSONConfigLoader{
  34. idKey: idKey,
  35. configKey: configKey,
  36. cache: cache,
  37. }
  38. }
  39. func (this *JSONConfigLoader) LoadWithID(raw []byte, id string) (interface{}, error) {
  40. creator, found := this.cache[id]
  41. if !found {
  42. return nil, ErrUnknownConfigID
  43. }
  44. config := creator()
  45. if err := json.Unmarshal(raw, config); err != nil {
  46. return nil, err
  47. }
  48. return config, nil
  49. }
  50. func (this *JSONConfigLoader) Load(raw []byte) (interface{}, string, error) {
  51. var obj map[string]json.RawMessage
  52. if err := json.Unmarshal(raw, &obj); err != nil {
  53. return nil, "", err
  54. }
  55. rawID, found := obj[this.idKey]
  56. if !found {
  57. log.Error(this.idKey, " not found in JSON content.")
  58. return nil, "", common.ErrObjectNotFound
  59. }
  60. var id string
  61. if err := json.Unmarshal(rawID, &id); err != nil {
  62. return nil, "", err
  63. }
  64. rawConfig := json.RawMessage(raw)
  65. if len(this.configKey) > 0 {
  66. configValue, found := obj[this.configKey]
  67. if !found {
  68. log.Error(this.configKey, " not found in JSON content.")
  69. return nil, "", common.ErrObjectNotFound
  70. }
  71. rawConfig = configValue
  72. }
  73. config, err := this.LoadWithID([]byte(rawConfig), id)
  74. if err != nil {
  75. return nil, id, err
  76. }
  77. return config, id, nil
  78. }