github.com/imannamdari/v2ray-core/v5@v5.0.5/main/commands/all/api/jsonv4/outbounds_add.go (about)

     1  package jsonv4
     2  
     3  import (
     4  	"fmt"
     5  
     6  	handlerService "github.com/imannamdari/v2ray-core/v5/app/proxyman/command"
     7  	"github.com/imannamdari/v2ray-core/v5/main/commands/all/api"
     8  	"github.com/imannamdari/v2ray-core/v5/main/commands/base"
     9  	"github.com/imannamdari/v2ray-core/v5/main/commands/helpers"
    10  )
    11  
    12  var cmdAddOutbounds = &base.Command{
    13  	CustomFlags: true,
    14  	UsageLine:   "{{.Exec}} api ado [--server=127.0.0.1:8080] [c1.json] [dir1]...",
    15  	Short:       "add outbounds",
    16  	Long: `
    17  Add outbounds to V2Ray.
    18  
    19  > Make sure you have "HandlerService" set in "config.api.services" 
    20  of server config.
    21  
    22  Arguments:
    23  
    24  	-format <format>
    25  		The input format.
    26  		Available values: "auto", "json", "toml", "yaml"
    27  		Default: "auto"
    28  
    29  	-r
    30  		Load folders recursively.
    31  
    32  	-s, -server <server:port>
    33  		The API server address. Default 127.0.0.1:8080
    34  
    35  	-t, -timeout <seconds>
    36  		Timeout seconds to call API. Default 3
    37  
    38  Example:
    39  
    40      {{.Exec}} {{.LongName}} dir
    41      {{.Exec}} {{.LongName}} c1.json c2.yaml
    42  `,
    43  	Run: executeAddOutbounds,
    44  }
    45  
    46  func executeAddOutbounds(cmd *base.Command, args []string) {
    47  	api.SetSharedFlags(cmd)
    48  	api.SetSharedConfigFlags(cmd)
    49  	cmd.Flag.Parse(args)
    50  	c, err := helpers.LoadConfig(cmd.Flag.Args(), api.APIConfigFormat, api.APIConfigRecursively)
    51  	if err != nil {
    52  		base.Fatalf("failed to load: %s", err)
    53  	}
    54  	if len(c.OutboundConfigs) == 0 {
    55  		base.Fatalf("no valid outbound found")
    56  	}
    57  
    58  	conn, ctx, close := api.DialAPIServer()
    59  	defer close()
    60  
    61  	client := handlerService.NewHandlerServiceClient(conn)
    62  	for _, out := range c.OutboundConfigs {
    63  		fmt.Println("adding:", out.Tag)
    64  		o, err := out.Build()
    65  		if err != nil {
    66  			base.Fatalf("failed to build conf: %s", err)
    67  		}
    68  		r := &handlerService.AddOutboundRequest{
    69  			Outbound: o,
    70  		}
    71  		_, err = client.AddOutbound(ctx, r)
    72  		if err != nil {
    73  			base.Fatalf("failed to add outbound: %s", err)
    74  		}
    75  	}
    76  }