mirror of
https://github.com/XTLS/Xray-core.git
synced 2025-04-30 01:08:33 +00:00
v1.0.0
This commit is contained in:
parent
47d23e9972
commit
c7f7c08ead
711 changed files with 82154 additions and 2 deletions
82
infra/conf/serial/loader.go
Normal file
82
infra/conf/serial/loader.go
Normal file
|
@ -0,0 +1,82 @@
|
|||
package serial
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
|
||||
"github.com/xtls/xray-core/v1/common/errors"
|
||||
"github.com/xtls/xray-core/v1/core"
|
||||
"github.com/xtls/xray-core/v1/infra/conf"
|
||||
json_reader "github.com/xtls/xray-core/v1/infra/conf/json"
|
||||
)
|
||||
|
||||
type offset struct {
|
||||
line int
|
||||
char int
|
||||
}
|
||||
|
||||
func findOffset(b []byte, o int) *offset {
|
||||
if o >= len(b) || o < 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
line := 1
|
||||
char := 0
|
||||
for i, x := range b {
|
||||
if i == o {
|
||||
break
|
||||
}
|
||||
if x == '\n' {
|
||||
line++
|
||||
char = 0
|
||||
} else {
|
||||
char++
|
||||
}
|
||||
}
|
||||
|
||||
return &offset{line: line, char: char}
|
||||
}
|
||||
|
||||
// DecodeJSONConfig reads from reader and decode the config into *conf.Config
|
||||
// syntax error could be detected.
|
||||
func DecodeJSONConfig(reader io.Reader) (*conf.Config, error) {
|
||||
jsonConfig := &conf.Config{}
|
||||
|
||||
jsonContent := bytes.NewBuffer(make([]byte, 0, 10240))
|
||||
jsonReader := io.TeeReader(&json_reader.Reader{
|
||||
Reader: reader,
|
||||
}, jsonContent)
|
||||
decoder := json.NewDecoder(jsonReader)
|
||||
|
||||
if err := decoder.Decode(jsonConfig); err != nil {
|
||||
var pos *offset
|
||||
cause := errors.Cause(err)
|
||||
switch tErr := cause.(type) {
|
||||
case *json.SyntaxError:
|
||||
pos = findOffset(jsonContent.Bytes(), int(tErr.Offset))
|
||||
case *json.UnmarshalTypeError:
|
||||
pos = findOffset(jsonContent.Bytes(), int(tErr.Offset))
|
||||
}
|
||||
if pos != nil {
|
||||
return nil, newError("failed to read config file at line ", pos.line, " char ", pos.char).Base(err)
|
||||
}
|
||||
return nil, newError("failed to read config file").Base(err)
|
||||
}
|
||||
|
||||
return jsonConfig, nil
|
||||
}
|
||||
|
||||
func LoadJSONConfig(reader io.Reader) (*core.Config, error) {
|
||||
jsonConfig, err := DecodeJSONConfig(reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pbConfig, err := jsonConfig.Build()
|
||||
if err != nil {
|
||||
return nil, newError("failed to parse json config").Base(err)
|
||||
}
|
||||
|
||||
return pbConfig, nil
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue