1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-06-20 14:35:23 +00:00
v2fly/common/loader/json_conf.go

67 lines
1.5 KiB
Go
Raw Normal View History

2016-06-10 20:26:39 +00:00
// +build json
package loader
import (
"encoding/json"
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
)
type JSONConfigLoader struct {
*BaseConfigLoader
idKey string
configKey string
}
func NewJSONConfigLoader(idKey string, configKey string) *JSONConfigLoader {
return &JSONConfigLoader{
idKey: idKey,
configKey: configKey,
BaseConfigLoader: NewBaseConfigLoader(),
}
}
func (this *JSONConfigLoader) LoadWithID(raw []byte, id string) (interface{}, error) {
config, err := this.CreateConfig(id)
if err != nil {
return nil, err
}
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
}