1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-09 03:37:37 -05:00
v2fly/infra/conf/jsonpb/jsonpb.go

72 lines
1.7 KiB
Go
Raw Normal View History

2021-06-19 10:00:22 -04:00
package jsonpb
import (
"bytes"
2021-10-28 06:34:19 -04:00
"io"
2021-06-19 10:00:22 -04:00
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
2021-10-28 06:34:19 -04:00
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/cmdarg"
"github.com/v2fly/v2ray-core/v5/common/serial"
2021-06-19 10:00:22 -04:00
)
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
2021-06-19 10:00:22 -04:00
func loadJSONPB(data io.Reader) (*core.Config, error) {
2021-06-19 10:00:22 -04:00
coreconf := &core.Config{}
jsonpbloader := &jsonpb.Unmarshaler{AnyResolver: serial.GetResolver()}
err := jsonpbloader.Unmarshal(data, coreconf)
if err != nil {
return nil, err
}
return coreconf, nil
}
func dumpJSONPb(config proto.Message, w io.Writer) error {
2021-06-19 10:00:22 -04:00
jsonpbdumper := &jsonpb.Marshaler{AnyResolver: serial.GetResolver()}
err := jsonpbdumper.Marshal(w, config)
if err != nil {
return err
}
return nil
}
func DumpJSONPb(config proto.Message, w io.Writer) error {
return dumpJSONPb(config, w)
2021-06-19 10:00:22 -04:00
}
2021-06-19 10:09:13 -04:00
const FormatProtobufJSONPB = "jsonpb"
2021-06-19 10:00:22 -04:00
func init() {
common.Must(core.RegisterConfigLoader(&core.ConfigFormat{
2021-06-19 10:09:13 -04:00
Name: []string{FormatProtobufJSONPB},
2021-06-19 10:00:22 -04:00
Extension: []string{".pb.json", ".pbjson"},
Loader: func(input interface{}) (*core.Config, error) {
switch v := input.(type) {
case string:
r, err := cmdarg.LoadArg(v)
if err != nil {
return nil, err
}
data, err := buf.ReadAllToBytes(r)
if err != nil {
return nil, err
}
return loadJSONPB(bytes.NewReader(data))
2021-06-19 10:00:22 -04:00
case io.Reader:
data, err := buf.ReadAllToBytes(v)
if err != nil {
return nil, err
}
return loadJSONPB(bytes.NewReader(data))
2021-06-19 10:00:22 -04:00
default:
2021-12-26 23:33:08 -05:00
return nil, newError("unknown type")
2021-06-19 10:00:22 -04:00
}
},
}))
}