json.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package convert
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. creflect "github.com/xtls/xray-core/common/reflect"
  7. cserial "github.com/xtls/xray-core/common/serial"
  8. "github.com/xtls/xray-core/main/commands/base"
  9. "github.com/xtls/xray-core/main/confloader"
  10. )
  11. var cmdJson = &base.Command{
  12. CustomFlags: true,
  13. UsageLine: "{{.Exec}} convert json [-type] [stdin:] [typedMessage file] ",
  14. Short: "Convert typedMessage to json",
  15. Long: `
  16. Convert ONE typedMessage to json.
  17. Where typedMessage file need to be in the following format:
  18. {
  19. "type": "xray.proxy.shadowsocks.Account",
  20. "value": "CgMxMTEQBg=="
  21. }
  22. Arguments:
  23. -t, -type
  24. Inject type infomation.
  25. Examples:
  26. {{.Exec}} convert json user.tmsg
  27. `,
  28. Run: executeTypedMessageToJson,
  29. }
  30. func executeTypedMessageToJson(cmd *base.Command, args []string) {
  31. var injectTypeInfo bool
  32. cmd.Flag.BoolVar(&injectTypeInfo, "t", false, "")
  33. cmd.Flag.BoolVar(&injectTypeInfo, "type", false, "")
  34. cmd.Flag.Parse(args)
  35. if cmd.Flag.NArg() < 1 {
  36. base.Fatalf("empty input list")
  37. }
  38. reader, err := confloader.LoadConfig(cmd.Flag.Arg(0))
  39. if err != nil {
  40. base.Fatalf("failed to load config: %s", err)
  41. }
  42. b, err := io.ReadAll(reader)
  43. if err != nil {
  44. base.Fatalf("failed to read config: %s", err)
  45. }
  46. tm := cserial.TypedMessage{}
  47. if err = json.Unmarshal(b, &tm); err != nil {
  48. base.Fatalf("failed to unmarshal config: %s", err)
  49. }
  50. if j, ok := creflect.MarshalToJson(&tm, injectTypeInfo); ok {
  51. fmt.Println(j)
  52. } else {
  53. base.Fatalf("marshal TypedMessage to json failed")
  54. }
  55. }