-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathapi.go
More file actions
78 lines (66 loc) · 1.75 KB
/
api.go
File metadata and controls
78 lines (66 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package api
import (
"bytes"
"encoding/json"
"io"
"net/http"
"os"
"github.com/MakeNowJust/heredoc/v2"
"github.com/OctopusDeploy/cli/pkg/apiclient"
"github.com/OctopusDeploy/cli/pkg/constants"
"github.com/OctopusDeploy/cli/pkg/constants/annotations"
"github.com/OctopusDeploy/cli/pkg/factory"
"github.com/spf13/cobra"
)
// OsExit is a variable so tests can stub it to avoid terminating the process.
var OsExit = os.Exit
func NewCmdAPI(f factory.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "api <url>",
Short: "Execute a raw API GET request",
Long: "Execute an authenticated GET request against the Octopus Server API and print the JSON response.",
Example: heredoc.Docf(`
$ %[1]s api /api
$ %[1]s api /api/spaces
$ %[1]s api /api/Spaces-1/projects
`, constants.ExecutableName),
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return apiRun(cmd, f, args[0])
},
Annotations: map[string]string{
annotations.IsCore: "true",
},
}
return cmd
}
func apiRun(cmd *cobra.Command, f factory.Factory, path string) error {
client, err := f.GetSystemClient(apiclient.NewRequester(cmd))
if err != nil {
return err
}
req, err := http.NewRequest("GET", path, nil)
if err != nil {
return err
}
resp, err := client.HttpSession().DoRawRequest(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
// Pretty-print if valid JSON, otherwise output raw
var prettyJSON bytes.Buffer
if err := json.Indent(&prettyJSON, body, "", " "); err == nil {
cmd.Println(prettyJSON.String())
} else {
cmd.Print(string(body))
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
OsExit(resp.StatusCode)
}
return nil
}