github.com/xtls/xray-core@v1.8.12-0.20240518155711-3168d27b0bdb/main/commands/all/api/rules_add.go (about) 1 package api 2 3 import ( 4 "fmt" 5 6 routerService "github.com/xtls/xray-core/app/router/command" 7 cserial "github.com/xtls/xray-core/common/serial" 8 "github.com/xtls/xray-core/infra/conf" 9 "github.com/xtls/xray-core/infra/conf/serial" 10 "github.com/xtls/xray-core/main/commands/base" 11 ) 12 13 var cmdAddRules = &base.Command{ 14 CustomFlags: true, 15 UsageLine: "{{.Exec}} api adrules [--server=127.0.0.1:8080] <c1.json> [c2.json]...", 16 Short: "Add routing rules", 17 Long: ` 18 Add routing rules to Xray. 19 Arguments: 20 -s, -server 21 The API server address. Default 127.0.0.1:8080 22 -t, -timeout 23 Timeout seconds to call API. Default 3 24 -append 25 append or replace config. Default false 26 27 Example: 28 {{.Exec}} {{.LongName}} --server=127.0.0.1:8080 c1.json c2.json 29 `, 30 Run: executeAddRules, 31 } 32 33 func executeAddRules(cmd *base.Command, args []string) { 34 var ( 35 shouldAppend bool 36 ) 37 setSharedFlags(cmd) 38 cmd.Flag.BoolVar(&shouldAppend, "append", false, "") 39 cmd.Flag.Parse(args) 40 41 unnamedArgs := cmd.Flag.Args() 42 if len(unnamedArgs) == 0 { 43 fmt.Println("reading from stdin:") 44 unnamedArgs = []string{"stdin:"} 45 } 46 conn, ctx, close := dialAPIServer() 47 defer close() 48 49 client := routerService.NewRoutingServiceClient(conn) 50 51 rcs := make([]conf.RouterConfig, 0) 52 for _, arg := range unnamedArgs { 53 r, err := loadArg(arg) 54 if err != nil { 55 base.Fatalf("failed to load %s: %s", arg, err) 56 } 57 conf, err := serial.DecodeJSONConfig(r) 58 if err != nil { 59 base.Fatalf("failed to decode %s: %s", arg, err) 60 } 61 rcs = append(rcs, *conf.RouterConfig) 62 } 63 if len(rcs) == 0 { 64 base.Fatalf("no valid rule found in config") 65 } 66 for _, in := range rcs { 67 68 config, err := in.Build() 69 if err != nil { 70 base.Fatalf("failed to build conf: %s", err) 71 } 72 tmsg := cserial.ToTypedMessage(config) 73 if tmsg == nil { 74 base.Fatalf("failed to format config to TypedMessage.") 75 } 76 77 ra := &routerService.AddRuleRequest{ 78 Config: tmsg, 79 ShouldAppend: shouldAppend, 80 } 81 resp, err := client.AddRule(ctx, ra) 82 if err != nil { 83 base.Fatalf("failed to perform AddRule: %s", err) 84 } 85 showJSONResponse(resp) 86 } 87 88 }