shared.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package api
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "os"
  7. "strings"
  8. "time"
  9. "github.com/v2fly/v2ray-core/v4/main/commands/base"
  10. "google.golang.org/grpc"
  11. "google.golang.org/protobuf/proto"
  12. core "github.com/v2fly/v2ray-core/v4"
  13. )
  14. var (
  15. apiServerAddrPtr string
  16. apiTimeout int
  17. apiJSON bool
  18. apiConfigFormat string
  19. apiConfigRecursively bool
  20. )
  21. func setSharedFlags(cmd *base.Command) {
  22. cmd.Flag.StringVar(&apiServerAddrPtr, "s", "127.0.0.1:8080", "")
  23. cmd.Flag.StringVar(&apiServerAddrPtr, "server", "127.0.0.1:8080", "")
  24. cmd.Flag.IntVar(&apiTimeout, "t", 3, "")
  25. cmd.Flag.IntVar(&apiTimeout, "timeout", 3, "")
  26. cmd.Flag.BoolVar(&apiJSON, "json", false, "")
  27. }
  28. func setSharedConfigFlags(cmd *base.Command) {
  29. cmd.Flag.StringVar(&apiConfigFormat, "format", core.FormatAuto, "")
  30. cmd.Flag.BoolVar(&apiConfigRecursively, "r", false, "")
  31. }
  32. func dialAPIServer() (conn *grpc.ClientConn, ctx context.Context, close func()) {
  33. ctx, cancel := context.WithTimeout(context.Background(), time.Duration(apiTimeout)*time.Second)
  34. conn = dialAPIServerWithContext(ctx)
  35. close = func() {
  36. cancel()
  37. conn.Close()
  38. }
  39. return
  40. }
  41. func dialAPIServerWithoutTimeout() (conn *grpc.ClientConn, ctx context.Context, close func()) {
  42. ctx = context.Background()
  43. conn = dialAPIServerWithContext(ctx)
  44. close = func() {
  45. conn.Close()
  46. }
  47. return
  48. }
  49. func dialAPIServerWithContext(ctx context.Context) (conn *grpc.ClientConn) {
  50. conn, err := grpc.DialContext(ctx, apiServerAddrPtr, grpc.WithInsecure(), grpc.WithBlock())
  51. if err != nil {
  52. base.Fatalf("failed to dial %s", apiServerAddrPtr)
  53. }
  54. return
  55. }
  56. func protoToJSONString(m proto.Message, prefix, indent string) (string, error) {
  57. b := new(strings.Builder)
  58. e := json.NewEncoder(b)
  59. e.SetIndent(prefix, indent)
  60. e.SetEscapeHTML(false)
  61. err := e.Encode(m)
  62. if err != nil {
  63. return "", err
  64. }
  65. return strings.TrimSpace(b.String()), nil
  66. }
  67. func showJSONResponse(m proto.Message) {
  68. output, err := protoToJSONString(m, "", "")
  69. if err != nil {
  70. fmt.Fprintf(os.Stdout, "%v\n", m)
  71. base.Fatalf("error encode json: %s", err)
  72. }
  73. fmt.Println(output)
  74. }