Skip to content

Commit f3dc545

Browse files
committed
Command: use reflect marshal to json as output
1 parent 498d8eb commit f3dc545

File tree

2 files changed

+16
-10
lines changed

2 files changed

+16
-10
lines changed

common/reflect/marshal.go

+11-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package reflect
22

33
import (
4+
"bytes"
45
"encoding/json"
56
"fmt"
67
"reflect"
@@ -13,13 +14,22 @@ import (
1314

1415
func MarshalToJson(v interface{}, insertTypeInfo bool) (string, bool) {
1516
if itf := marshalInterface(v, true, insertTypeInfo); itf != nil {
16-
if b, err := json.MarshalIndent(itf, "", " "); err == nil {
17+
if b, err := JSONMarshalWithoutEscape(itf); err == nil {
1718
return string(b[:]), true
1819
}
1920
}
2021
return "", false
2122
}
2223

24+
func JSONMarshalWithoutEscape(t interface{}) ([]byte, error) {
25+
buffer := &bytes.Buffer{}
26+
encoder := json.NewEncoder(buffer)
27+
encoder.SetIndent("", " ")
28+
encoder.SetEscapeHTML(false)
29+
err := encoder.Encode(t)
30+
return buffer.Bytes(), err
31+
}
32+
2333
func marshalTypedMessage(v *cserial.TypedMessage, ignoreNullValue bool, insertTypeInfo bool) interface{} {
2434
if v == nil {
2535
return nil

main/commands/all/api/shared.go

+5-9
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,10 @@ import (
1313
"time"
1414

1515
"google.golang.org/grpc/credentials/insecure"
16-
"google.golang.org/protobuf/encoding/protojson"
1716

1817
"github.com/xtls/xray-core/common/buf"
1918
"github.com/xtls/xray-core/main/commands/base"
19+
creflect "github.com/xtls/xray-core/common/reflect"
2020
"google.golang.org/grpc"
2121
"google.golang.org/protobuf/proto"
2222
)
@@ -107,20 +107,16 @@ func fetchHTTPContent(target string) ([]byte, error) {
107107
return content, nil
108108
}
109109

110-
func protoToJSONString(m proto.Message, prefix, indent string) (string, error) {
111-
return strings.TrimSpace(protojson.MarshalOptions{Indent: indent}.Format(m)), nil
112-
}
113-
114110
func showJSONResponse(m proto.Message) {
115111
if isNil(m) {
116112
return
117113
}
118-
output, err := protoToJSONString(m, "", " ")
119-
if err != nil {
114+
if j, ok := creflect.MarshalToJson(m, true); ok {
115+
fmt.Println(j)
116+
} else {
120117
fmt.Fprintf(os.Stdout, "%v\n", m)
121-
base.Fatalf("error encode json: %s", err)
118+
base.Fatalf("error encode json")
122119
}
123-
fmt.Println(output)
124120
}
125121

126122
func isNil(i interface{}) bool {

0 commit comments

Comments
 (0)