You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
v2ray-core/tools/conf/loader.go

91 lines
2.0 KiB

package conf
import (
"encoding/json"
"v2ray.com/core/common"
"v2ray.com/core/common/errors"
"v2ray.com/core/common/log"
)
var (
ErrUnknownConfigID = errors.New("Unknown config ID.")
)
type ConfigCreator func() interface{}
type ConfigCreatorCache map[string]ConfigCreator
8 years ago
func (v ConfigCreatorCache) RegisterCreator(id string, creator ConfigCreator) error {
if _, found := v[id]; found {
return common.ErrDuplicatedName
}
8 years ago
v[id] = creator
return nil
}
8 years ago
func (v ConfigCreatorCache) CreateConfig(id string) (interface{}, error) {
creator, found := v[id]
if !found {
return nil, ErrUnknownConfigID
}
return creator(), nil
}
type JSONConfigLoader struct {
cache ConfigCreatorCache
idKey string
configKey string
}
func NewJSONConfigLoader(cache ConfigCreatorCache, idKey string, configKey string) *JSONConfigLoader {
return &JSONConfigLoader{
idKey: idKey,
configKey: configKey,
cache: cache,
}
}
8 years ago
func (v *JSONConfigLoader) LoadWithID(raw []byte, id string) (interface{}, error) {
creator, found := v.cache[id]
if !found {
return nil, ErrUnknownConfigID
}
config := creator()
if err := json.Unmarshal(raw, config); err != nil {
return nil, err
}
return config, nil
}
8 years ago
func (v *JSONConfigLoader) Load(raw []byte) (interface{}, string, error) {
var obj map[string]json.RawMessage
if err := json.Unmarshal(raw, &obj); err != nil {
return nil, "", err
}
8 years ago
rawID, found := obj[v.idKey]
if !found {
8 years ago
log.Error(v.idKey, " not found in JSON content.")
return nil, "", common.ErrObjectNotFound
}
var id string
if err := json.Unmarshal(rawID, &id); err != nil {
return nil, "", err
}
rawConfig := json.RawMessage(raw)
8 years ago
if len(v.configKey) > 0 {
configValue, found := obj[v.configKey]
if !found {
8 years ago
log.Error(v.configKey, " not found in JSON content.")
return nil, "", common.ErrObjectNotFound
}
rawConfig = configValue
}
8 years ago
config, err := v.LoadWithID([]byte(rawConfig), id)
if err != nil {
return nil, id, err
}
return config, id, nil
}