loader.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package conf
  2. import (
  3. "encoding/json"
  4. "v2ray.com/core/common"
  5. "v2ray.com/core/common/errors"
  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 (v ConfigCreatorCache) RegisterCreator(id string, creator ConfigCreator) error {
  14. if _, found := v[id]; found {
  15. return common.ErrDuplicatedName
  16. }
  17. v[id] = creator
  18. return nil
  19. }
  20. func (v ConfigCreatorCache) CreateConfig(id string) (interface{}, error) {
  21. creator, found := v[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 (v *JSONConfigLoader) LoadWithID(raw []byte, id string) (interface{}, error) {
  40. creator, found := v.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 (v *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[v.idKey]
  56. if !found {
  57. log.Error(v.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(v.configKey) > 0 {
  66. configValue, found := obj[v.configKey]
  67. if !found {
  68. log.Error(v.configKey, " not found in JSON content.")
  69. return nil, "", common.ErrObjectNotFound
  70. }
  71. rawConfig = configValue
  72. }
  73. config, err := v.LoadWithID([]byte(rawConfig), id)
  74. if err != nil {
  75. return nil, id, err
  76. }
  77. return config, id, nil
  78. }