From f0547bc04d5402c59e365a9fc3917d4d7756684f Mon Sep 17 00:00:00 2001 From: yuhan6665 <1588741+yuhan6665@users.noreply.github.com> Date: Thu, 8 Aug 2024 00:41:19 -0400 Subject: [PATCH] Commands: Use creflect.MarshalToJson() as output (#3674) --- common/reflect/marshal.go | 12 +++++++++++- main/commands/all/api/shared.go | 14 +++++--------- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/common/reflect/marshal.go b/common/reflect/marshal.go index dce34168..6d9798cc 100644 --- a/common/reflect/marshal.go +++ b/common/reflect/marshal.go @@ -1,6 +1,7 @@ package reflect import ( + "bytes" "encoding/json" "fmt" "reflect" @@ -13,13 +14,22 @@ import ( func MarshalToJson(v interface{}, insertTypeInfo bool) (string, bool) { if itf := marshalInterface(v, true, insertTypeInfo); itf != nil { - if b, err := json.MarshalIndent(itf, "", " "); err == nil { + if b, err := JSONMarshalWithoutEscape(itf); err == nil { return string(b[:]), true } } return "", false } +func JSONMarshalWithoutEscape(t interface{}) ([]byte, error) { + buffer := &bytes.Buffer{} + encoder := json.NewEncoder(buffer) + encoder.SetIndent("", " ") + encoder.SetEscapeHTML(false) + err := encoder.Encode(t) + return buffer.Bytes(), err +} + func marshalTypedMessage(v *cserial.TypedMessage, ignoreNullValue bool, insertTypeInfo bool) interface{} { if v == nil { return nil diff --git a/main/commands/all/api/shared.go b/main/commands/all/api/shared.go index 751b8615..870ef5fc 100644 --- a/main/commands/all/api/shared.go +++ b/main/commands/all/api/shared.go @@ -13,10 +13,10 @@ import ( "time" "google.golang.org/grpc/credentials/insecure" - "google.golang.org/protobuf/encoding/protojson" "github.com/xtls/xray-core/common/buf" "github.com/xtls/xray-core/main/commands/base" + creflect "github.com/xtls/xray-core/common/reflect" "google.golang.org/grpc" "google.golang.org/protobuf/proto" ) @@ -107,20 +107,16 @@ func fetchHTTPContent(target string) ([]byte, error) { return content, nil } -func protoToJSONString(m proto.Message, prefix, indent string) (string, error) { - return strings.TrimSpace(protojson.MarshalOptions{Indent: indent}.Format(m)), nil -} - func showJSONResponse(m proto.Message) { if isNil(m) { return } - output, err := protoToJSONString(m, "", " ") - if err != nil { + if j, ok := creflect.MarshalToJson(m, true); ok { + fmt.Println(j) + } else { fmt.Fprintf(os.Stdout, "%v\n", m) - base.Fatalf("error encode json: %s", err) + base.Fatalf("error encode json") } - fmt.Println(output) } func isNil(i interface{}) bool {