mirror of
https://github.com/XTLS/Xray-core.git
synced 2025-04-30 17:38:41 +00:00
v1.0.0
This commit is contained in:
parent
47d23e9972
commit
c7f7c08ead
711 changed files with 82154 additions and 2 deletions
83
infra/conf/loader.go
Normal file
83
infra/conf/loader.go
Normal file
|
@ -0,0 +1,83 @@
|
|||
package conf
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type ConfigCreator func() interface{}
|
||||
|
||||
type ConfigCreatorCache map[string]ConfigCreator
|
||||
|
||||
func (v ConfigCreatorCache) RegisterCreator(id string, creator ConfigCreator) error {
|
||||
if _, found := v[id]; found {
|
||||
return newError(id, " already registered.").AtError()
|
||||
}
|
||||
|
||||
v[id] = creator
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v ConfigCreatorCache) CreateConfig(id string) (interface{}, error) {
|
||||
creator, found := v[id]
|
||||
if !found {
|
||||
return nil, newError("unknown config id: ", id)
|
||||
}
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
func (v *JSONConfigLoader) LoadWithID(raw []byte, id string) (interface{}, error) {
|
||||
id = strings.ToLower(id)
|
||||
config, err := v.cache.CreateConfig(id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := json.Unmarshal(raw, config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return config, nil
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
rawID, found := obj[v.idKey]
|
||||
if !found {
|
||||
return nil, "", newError(v.idKey, " not found in JSON context").AtError()
|
||||
}
|
||||
var id string
|
||||
if err := json.Unmarshal(rawID, &id); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
rawConfig := json.RawMessage(raw)
|
||||
if len(v.configKey) > 0 {
|
||||
configValue, found := obj[v.configKey]
|
||||
if found {
|
||||
rawConfig = configValue
|
||||
} else {
|
||||
// Default to empty json object.
|
||||
rawConfig = json.RawMessage([]byte("{}"))
|
||||
}
|
||||
}
|
||||
config, err := v.LoadWithID([]byte(rawConfig), id)
|
||||
if err != nil {
|
||||
return nil, id, err
|
||||
}
|
||||
return config, id, nil
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue