v2ray-core/tools/conf/loader.go

92 lines
2.0 KiB
Go
Raw Normal View History

2016-10-17 12:35:13 +00:00
package conf
2016-06-10 20:26:39 +00:00
import (
"encoding/json"
2016-10-17 12:35:13 +00:00
"errors"
2016-06-10 20:26:39 +00:00
2016-08-20 18:55:45 +00:00
"v2ray.com/core/common"
"v2ray.com/core/common/log"
2016-06-10 20:26:39 +00:00
)
2016-10-17 12:35:13 +00:00
var (
ErrUnknownConfigID = errors.New("Unknown config ID.")
)
type ConfigCreator func() interface{}
type ConfigCreatorCache map[string]ConfigCreator
func (this ConfigCreatorCache) RegisterCreator(id string, creator ConfigCreator) error {
if _, found := this[id]; found {
return common.ErrDuplicatedName
}
this[id] = creator
return nil
}
func (this ConfigCreatorCache) CreateConfig(id string) (interface{}, error) {
creator, found := this[id]
if !found {
return nil, ErrUnknownConfigID
}
return creator(), nil
}
2016-10-16 12:22:21 +00:00
2016-06-10 20:26:39 +00:00
type JSONConfigLoader struct {
2016-10-17 12:35:13 +00:00
cache ConfigCreatorCache
2016-06-10 20:26:39 +00:00
idKey string
configKey string
}
2016-10-17 12:35:13 +00:00
func NewJSONConfigLoader(cache ConfigCreatorCache, idKey string, configKey string) *JSONConfigLoader {
2016-06-10 20:26:39 +00:00
return &JSONConfigLoader{
2016-09-21 11:52:16 +00:00
idKey: idKey,
configKey: configKey,
cache: cache,
2016-06-10 20:26:39 +00:00
}
}
func (this *JSONConfigLoader) LoadWithID(raw []byte, id string) (interface{}, error) {
2016-10-17 12:35:13 +00:00
creator, found := this.cache[id]
if !found {
return nil, ErrUnknownConfigID
2016-06-10 20:26:39 +00:00
}
2016-10-17 12:35:13 +00:00
config := creator()
2016-06-10 20:26:39 +00:00
if err := json.Unmarshal(raw, config); err != nil {
return nil, err
}
return config, nil
}
2016-08-06 19:59:22 +00:00
func (this *JSONConfigLoader) Load(raw []byte) (interface{}, string, error) {
2016-06-10 21:01:17 +00:00
var obj map[string]json.RawMessage
if err := json.Unmarshal(raw, &obj); err != nil {
2016-08-06 19:59:22 +00:00
return nil, "", err
2016-06-10 20:26:39 +00:00
}
rawID, found := obj[this.idKey]
if !found {
log.Error(this.idKey, " not found in JSON content.")
2016-08-18 06:34:21 +00:00
return nil, "", common.ErrObjectNotFound
2016-06-10 20:26:39 +00:00
}
var id string
2016-06-10 21:01:17 +00:00
if err := json.Unmarshal(rawID, &id); err != nil {
2016-08-06 19:59:22 +00:00
return nil, "", err
2016-06-10 20:26:39 +00:00
}
rawConfig := json.RawMessage(raw)
if len(this.configKey) > 0 {
configValue, found := obj[this.configKey]
if !found {
log.Error(this.configKey, " not found in JSON content.")
2016-08-18 06:34:21 +00:00
return nil, "", common.ErrObjectNotFound
2016-06-10 20:26:39 +00:00
}
rawConfig = configValue
}
2016-08-06 19:59:22 +00:00
config, err := this.LoadWithID([]byte(rawConfig), id)
if err != nil {
return nil, id, err
}
return config, id, nil
2016-06-10 20:26:39 +00:00
}