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
|
|
|
|
2022-01-02 10:16:23 -05: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
|
|
|
)
|
|
|
|
|
2022-01-02 10:16:23 -05:00
|
|
|
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
|
2021-06-19 10:00:22 -04:00
|
|
|
|
2021-11-27 04:16:41 -05: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
|
|
|
|
}
|
|
|
|
|
2021-11-27 04:16:41 -05:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2021-11-27 04:16:41 -05:00
|
|
|
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
|
|
|
|
}
|
2021-11-27 04:16:41 -05:00
|
|
|
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
|
|
|
|
}
|
2021-11-27 04:16:41 -05:00
|
|
|
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
|
|
|
}
|
|
|
|
},
|
|
|
|
}))
|
|
|
|
}
|