1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-09-07 04:24:23 -04:00
v2fly/common/loader/json_conf.go

69 lines
1.5 KiB
Go
Raw Normal View History

2016-06-10 16:26:39 -04:00
// +build json
package loader
import (
"encoding/json"
2016-08-20 14:55:45 -04:00
"v2ray.com/core/common"
"v2ray.com/core/common/log"
2016-06-10 16:26:39 -04:00
)
2016-10-16 08:22:21 -04:00
type NamedTypeMap map[string]string
2016-06-10 16:26:39 -04:00
type JSONConfigLoader struct {
2016-10-16 08:22:21 -04:00
cache NamedTypeMap
2016-06-10 16:26:39 -04:00
idKey string
configKey string
}
2016-10-16 08:22:21 -04:00
func NewJSONConfigLoader(cache NamedTypeMap, idKey string, configKey string) *JSONConfigLoader {
2016-06-10 16:26:39 -04:00
return &JSONConfigLoader{
2016-09-21 07:52:16 -04:00
idKey: idKey,
configKey: configKey,
cache: cache,
2016-06-10 16:26:39 -04:00
}
}
func (this *JSONConfigLoader) LoadWithID(raw []byte, id string) (interface{}, error) {
2016-10-16 08:22:21 -04:00
config, err := GetInstance(this.cache[id])
2016-06-10 16:26:39 -04:00
if err != nil {
return nil, err
}
if err := json.Unmarshal(raw, config); err != nil {
return nil, err
}
return config, nil
}
2016-08-06 15:59:22 -04:00
func (this *JSONConfigLoader) Load(raw []byte) (interface{}, string, error) {
2016-06-10 17:01:17 -04:00
var obj map[string]json.RawMessage
if err := json.Unmarshal(raw, &obj); err != nil {
2016-08-06 15:59:22 -04:00
return nil, "", err
2016-06-10 16:26:39 -04:00
}
rawID, found := obj[this.idKey]
if !found {
log.Error(this.idKey, " not found in JSON content.")
2016-08-18 02:34:21 -04:00
return nil, "", common.ErrObjectNotFound
2016-06-10 16:26:39 -04:00
}
var id string
2016-06-10 17:01:17 -04:00
if err := json.Unmarshal(rawID, &id); err != nil {
2016-08-06 15:59:22 -04:00
return nil, "", err
2016-06-10 16:26:39 -04: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 02:34:21 -04:00
return nil, "", common.ErrObjectNotFound
2016-06-10 16:26:39 -04:00
}
rawConfig = configValue
}
2016-08-06 15:59:22 -04:00
config, err := this.LoadWithID([]byte(rawConfig), id)
if err != nil {
return nil, id, err
}
return config, id, nil
2016-06-10 16:26:39 -04:00
}