Skip to content

Commit c534a00

Browse files
committed
support call any api with command 'ucloud api'
1 parent c636e1b commit c534a00

4 files changed

Lines changed: 178 additions & 8 deletions

File tree

README-CN.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,3 +216,39 @@ gssh[uga-0psxxx] created
216216
$ ssh root@152.32.140.92.ipssh.net
217217
root@152.32.140.92.ipssh.net's password: password of the uhost instance
218218
```
219+
220+
使用"ucloud api"命令调用任意API,根据API文档把某个API的参数依次填入。此命令比较特殊,不支持--public-key,--private-key,--debug,--profile,--timeout-sec等公共参数,如果要开启debug模式,可以设置环境变量$UCLOUD_CLI_DEBUG=on
221+
222+
```
223+
$ ucloud api --Action <APIName> --Param1 <value> --Param2 <value> ...
224+
```
225+
或者把API参数写到JSON文件中,举例如下
226+
```
227+
$ ucloud api --local-file ./create_uhost.json
228+
229+
//create_uhost.json文件内容
230+
{
231+
"Action":"CreateUHostInstance",
232+
"Region":"cn-bj2",
233+
"Zone":"cn-bj2-02",
234+
"ImageId":"uimage-gk2x3x",
235+
"NetworkInterface": [{
236+
"EIP":{
237+
"Bandwidth":1,
238+
"OperatorName":"Bgp",
239+
"PayMode": "Bandwidth"
240+
}
241+
}],
242+
"LoginMode":"Password",
243+
"Password":"dGVzdGx4ajEy",
244+
"CPU":1,
245+
"Memory":2048,
246+
"Disks":[
247+
{
248+
"Size":20,
249+
"Type":"LOCAL_NORMAL",
250+
"IsBoot":"true"
251+
}
252+
]
253+
}
254+
```

README.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,3 +225,39 @@ gssh[uga-0psxxx] created
225225
$ ssh root@152.32.140.92.ipssh.net
226226
root@152.32.140.92.ipssh.net's password: password of the uhost instance
227227
```
228+
229+
Using command "ucloud api" to call any API.Fill in the parameters of an API in sequence according to the API documentation. This command is quite special, and public parameters such as --public-key,--private-key,--debug,--profile,--timeout-sec are not supported. If you want to tune on debug mode, set environment variable $UCLOUD_CLI_DEBUG=on
230+
231+
```
232+
$ ucloud api --Action <APIName> --Param1 <value> --Param2 <value> ...
233+
```
234+
You can also put those API parameters into a json file, like this.
235+
```
236+
$ ucloud api --local-file ./create_uhost.json
237+
238+
//create_uhost.json文件内容
239+
{
240+
"Action":"CreateUHostInstance",
241+
"Region":"cn-bj2",
242+
"Zone":"cn-bj2-02",
243+
"ImageId":"uimage-gk2x3x",
244+
"NetworkInterface": [{
245+
"EIP":{
246+
"Bandwidth":1,
247+
"OperatorName":"Bgp",
248+
"PayMode": "Bandwidth"
249+
}
250+
}],
251+
"LoginMode":"Password",
252+
"Password":"dGVzdGx4ajEy",
253+
"CPU":1,
254+
"Memory":2048,
255+
"Disks":[
256+
{
257+
"Size":20,
258+
"Type":"LOCAL_NORMAL",
259+
"IsBoot":"true"
260+
}
261+
]
262+
}
263+
```

cmd/api.go

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
package cmd
2+
3+
import (
4+
"encoding/json"
5+
"errors"
6+
"fmt"
7+
"io"
8+
"io/ioutil"
9+
"strings"
10+
11+
"github.com/spf13/cobra"
12+
13+
"github.com/ucloud/ucloud-cli/base"
14+
)
15+
16+
//NewCmdAPI ucloud api --xkey xvalue
17+
func NewCmdAPI(out io.Writer) *cobra.Command {
18+
return &cobra.Command{
19+
Use: "api",
20+
Short: "Call API",
21+
Long: "Call API",
22+
Run: func(c *cobra.Command, args []string) {
23+
params, err := parseParamsFromCmdLine(args)
24+
if err != nil {
25+
fmt.Fprintln(out, err)
26+
return
27+
}
28+
29+
if params["local-file"] != nil {
30+
file, ok := params["local-file"].(string)
31+
if !ok {
32+
fmt.Fprintf(out, "local-file should be a string\n")
33+
}
34+
params, err = parseParamsFromJSONFile(file)
35+
if err != nil {
36+
fmt.Fprintln(out, err)
37+
return
38+
}
39+
}
40+
41+
req := base.BizClient.UAccountClient.NewGenericRequest()
42+
err = req.SetPayload(params)
43+
if err != nil {
44+
fmt.Fprintf(out, "error: %v\n", err)
45+
return
46+
}
47+
48+
resp, err := base.BizClient.UAccountClient.GenericInvoke(req)
49+
if err != nil {
50+
fmt.Fprintf(out, "error: %v\n", err)
51+
return
52+
}
53+
54+
data, err := json.MarshalIndent(resp.GetPayload(), "", " ")
55+
if err != nil {
56+
fmt.Fprintf(out, "error: %v\n", err)
57+
return
58+
}
59+
fmt.Fprintln(out, string(data))
60+
},
61+
}
62+
}
63+
64+
func parseParamsFromJSONFile(path string) (map[string]interface{}, error) {
65+
content, err := ioutil.ReadFile(path)
66+
if err != nil {
67+
return nil, fmt.Errorf("read file error: %w", err)
68+
}
69+
params := make(map[string]interface{})
70+
err = json.Unmarshal(content, &params)
71+
if err != nil {
72+
return nil, fmt.Errorf("parse json error: %w", err)
73+
}
74+
return params, err
75+
}
76+
77+
func parseParamsFromCmdLine(args []string) (map[string]interface{}, error) {
78+
if len(args)%2 != 0 {
79+
return nil, errors.New("the key value pairs of api parameters do not match")
80+
}
81+
params := make(map[string]interface{})
82+
for i := 0; i < len(args)-1; i += 2 {
83+
if strings.HasPrefix(args[i], "--") {
84+
args[i] = args[i][2:]
85+
}
86+
params[args[i]] = args[i+1]
87+
}
88+
return params, nil
89+
}

cmd/root.go

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,8 @@ import (
2121

2222
"github.com/spf13/cobra"
2323

24-
"github.com/ucloud/ucloud-sdk-go/ucloud/log"
25-
2624
"github.com/ucloud/ucloud-cli/base"
25+
"github.com/ucloud/ucloud-sdk-go/ucloud/log"
2726
)
2827

2928
var global = &base.Global
@@ -129,6 +128,7 @@ func addChildren(root *cobra.Command) {
129128
root.AddCommand(NewCmdRedis())
130129
root.AddCommand(NewCmdMemcache())
131130
root.AddCommand(NewCmdExt())
131+
root.AddCommand(NewCmdAPI(out))
132132
for _, c := range root.Commands() {
133133
if c.Name() != "init" && c.Name() != "gendoc" && c.Name() != "config" {
134134
c.PersistentFlags().StringVar(&global.PublicKey, "public-key", global.PublicKey, "Set public-key to override the public-key in local config file")
@@ -152,7 +152,22 @@ func Execute() {
152152
}
153153
}
154154
base.InitConfig()
155+
mode := os.Getenv("UCLOUD_CLI_DEBUG")
156+
if mode == "on" || global.Debug {
157+
base.ClientConfig.LogLevel = log.DebugLevel
158+
base.BizClient = base.NewClient(base.ClientConfig, base.AuthCredential)
159+
}
160+
155161
addChildren(cmd)
162+
163+
targetCmd, flags, err := cmd.Find(os.Args[1:])
164+
if err == nil {
165+
if targetCmd.Use == "api" {
166+
targetCmd.Run(targetCmd, flags)
167+
return
168+
}
169+
}
170+
156171
if err := cmd.Execute(); err != nil {
157172
os.Exit(1)
158173
}
@@ -220,12 +235,6 @@ func initialize(cmd *cobra.Command) {
220235
base.ClientConfig.Zone = zone
221236
}
222237

223-
mode := os.Getenv("UCLOUD_CLI_DEBUG")
224-
if mode == "on" || global.Debug {
225-
base.ClientConfig.LogLevel = log.DebugLevel
226-
base.BizClient = base.NewClient(base.ClientConfig, base.AuthCredential)
227-
}
228-
229238
if (cmd.Name() != "config" && cmd.Name() != "init" && cmd.Name() != "version") && (cmd.Parent() != nil && cmd.Parent().Name() != "config") {
230239
if base.InCloudShell {
231240
return

0 commit comments

Comments
 (0)