mirror of
https://github.com/v2fly/v2ray-core.git
synced 2024-11-10 06:16:53 -05:00
2523d77919
(rebased from ebbf31f07e
)
86 lines
2.1 KiB
Go
86 lines
2.1 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/v2fly/v2ray-core/v4/main/commands/base"
|
|
"google.golang.org/grpc"
|
|
"google.golang.org/protobuf/proto"
|
|
|
|
core "github.com/v2fly/v2ray-core/v4"
|
|
)
|
|
|
|
var (
|
|
apiServerAddrPtr string
|
|
apiTimeout int
|
|
apiJSON bool
|
|
apiConfigFormat string
|
|
apiConfigRecursively bool
|
|
)
|
|
|
|
func setSharedFlags(cmd *base.Command) {
|
|
cmd.Flag.StringVar(&apiServerAddrPtr, "s", "127.0.0.1:8080", "")
|
|
cmd.Flag.StringVar(&apiServerAddrPtr, "server", "127.0.0.1:8080", "")
|
|
cmd.Flag.IntVar(&apiTimeout, "t", 3, "")
|
|
cmd.Flag.IntVar(&apiTimeout, "timeout", 3, "")
|
|
cmd.Flag.BoolVar(&apiJSON, "json", false, "")
|
|
}
|
|
|
|
func setSharedConfigFlags(cmd *base.Command) {
|
|
cmd.Flag.StringVar(&apiConfigFormat, "format", core.FormatAuto, "")
|
|
cmd.Flag.BoolVar(&apiConfigRecursively, "r", false, "")
|
|
}
|
|
|
|
func dialAPIServer() (conn *grpc.ClientConn, ctx context.Context, close func()) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(apiTimeout)*time.Second)
|
|
conn = dialAPIServerWithContext(ctx)
|
|
close = func() {
|
|
cancel()
|
|
conn.Close()
|
|
}
|
|
return
|
|
}
|
|
|
|
func dialAPIServerWithoutTimeout() (conn *grpc.ClientConn, ctx context.Context, close func()) {
|
|
ctx = context.Background()
|
|
conn = dialAPIServerWithContext(ctx)
|
|
close = func() {
|
|
conn.Close()
|
|
}
|
|
return
|
|
}
|
|
|
|
func dialAPIServerWithContext(ctx context.Context) (conn *grpc.ClientConn) {
|
|
conn, err := grpc.DialContext(ctx, apiServerAddrPtr, grpc.WithInsecure(), grpc.WithBlock())
|
|
if err != nil {
|
|
base.Fatalf("failed to dial %s", apiServerAddrPtr)
|
|
}
|
|
return
|
|
}
|
|
|
|
func protoToJSONString(m proto.Message, prefix, indent string) (string, error) {
|
|
b := new(strings.Builder)
|
|
e := json.NewEncoder(b)
|
|
e.SetIndent(prefix, indent)
|
|
e.SetEscapeHTML(false)
|
|
err := e.Encode(m)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return strings.TrimSpace(b.String()), nil
|
|
}
|
|
|
|
func showJSONResponse(m proto.Message) {
|
|
output, err := protoToJSONString(m, "", "")
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stdout, "%v\n", m)
|
|
base.Fatalf("error encode json: %s", err)
|
|
}
|
|
fmt.Println(output)
|
|
}
|