-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathcurl.go
240 lines (216 loc) · 7.54 KB
/
curl.go
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
package curl
import (
"bytes"
"fmt"
"io"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strings"
"time"
"github.com/stackitcloud/stackit-cli/internal/pkg/args"
"github.com/stackitcloud/stackit-cli/internal/pkg/auth"
"github.com/stackitcloud/stackit-cli/internal/pkg/errors"
"github.com/stackitcloud/stackit-cli/internal/pkg/examples"
"github.com/stackitcloud/stackit-cli/internal/pkg/flags"
"github.com/stackitcloud/stackit-cli/internal/pkg/print"
"github.com/spf13/cobra"
)
const (
requestMethodFlag = "request"
headerFlag = "header"
dataFlag = "data"
includeResponseHeadersFlag = "include"
failOnHTTPErrorFlag = "fail"
outputFileFlag = "output"
)
const (
urlArg = "URL"
)
type inputModel struct {
URL string
RequestMethod string
Headers []string
Data *string
IncludeResponseHeaders bool
FailOnHTTPError bool
OutputFile *string
}
func NewCmd(p *print.Printer) *cobra.Command {
cmd := &cobra.Command{
Use: fmt.Sprintf("curl %s", urlArg),
Short: "Executes an authenticated HTTP request to an endpoint",
Long: "Executes an HTTP request to an endpoint, using the authentication provided by the CLI.",
Example: examples.Build(
examples.NewExample(
"Get all the DNS zones for project with ID xxx via GET request to https://dns.api.stackit.cloud/v1/projects/xxx/zones",
"$ stackit curl https://dns.api.stackit.cloud/v1/projects/xxx/zones",
),
examples.NewExample(
`Get all the DNS zones for project with ID xxx via GET request to https://dns.api.stackit.cloud/v1/projects/xxx/zones, write complete response (headers and body) to file "./output.txt"`,
"$ stackit curl https://dns.api.stackit.cloud/v1/projects/xxx/zones -include --output ./output.txt",
),
examples.NewExample(
`Create a new DNS zone for project with ID xxx via POST request to https://dns.api.stackit.cloud/v1/projects/xxx/zones with payload from file "./payload.json"`,
`$ stackit curl https://dns.api.stackit.cloud/v1/projects/xxx/zones -X POST --data @./payload.json`,
),
examples.NewExample(
`Get all the DNS zones for project with ID xxx via GET request to https://dns.api.stackit.cloud/v1/projects/xxx/zones, with header "Authorization: Bearer yyy", fail if server returns error (such as 403 Forbidden)`,
`$ stackit curl https://dns.api.stackit.cloud/v1/projects/xxx/zones -X POST -H "Authorization: Bearer yyy" --fail`,
),
),
Args: args.SingleArg(urlArg, validateURL),
RunE: func(cmd *cobra.Command, args []string) (err error) {
model, err := parseInput(p, cmd, args)
if err != nil {
return err
}
bearerToken, err := getBearerToken(p)
if err != nil {
return err
}
req, err := buildRequest(model, bearerToken)
if err != nil {
return err
}
client := http.Client{
Timeout: 30 * time.Second,
}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("do request: %w", err)
}
defer func() {
closeErr := resp.Body.Close()
if closeErr != nil {
err = fmt.Errorf("close response body: %w", closeErr)
}
}()
err = outputResponse(p, model, resp)
if err != nil {
return err
}
if model.FailOnHTTPError && resp.StatusCode >= 400 {
os.Exit(22)
}
return nil
},
}
configureFlags(cmd)
return cmd
}
func validateURL(value string) error {
urlStruct, err := url.Parse(value)
if err != nil {
return fmt.Errorf("parse URL: %w", err)
}
urlHost := urlStruct.Hostname()
if urlHost == "" {
return fmt.Errorf("bad url")
}
if !strings.HasSuffix(urlHost, "stackit.cloud") {
return fmt.Errorf("only urls belonging to STACKIT are permitted, hostname must end in stackit.cloud")
}
return nil
}
func configureFlags(cmd *cobra.Command) {
requestMethodOptions := []string{
http.MethodGet,
http.MethodHead,
http.MethodPost,
http.MethodPut,
http.MethodPatch,
http.MethodDelete,
http.MethodConnect,
http.MethodOptions,
http.MethodTrace,
}
headerFlagUsage := `Custom headers to include in the request, can be specified multiple times. If the "Authorization" header is set, it will override the authentication provided by the CLI`
cmd.Flags().VarP(flags.EnumFlag(true, "", requestMethodOptions...), requestMethodFlag, "X", "HTTP method, defaults to GET")
cmd.Flags().StringSliceP(headerFlag, "H", []string{}, headerFlagUsage)
cmd.Flags().Var(flags.ReadFromFileFlag(), dataFlag, `Content to include in the request body. Can be a string or a file path prefixed with "@"`)
cmd.Flags().Bool(includeResponseHeadersFlag, false, "If set, response headers are added to the output")
cmd.Flags().Bool(failOnHTTPErrorFlag, false, "If set, exits with error 22 if response code is 4XX or 5XX")
cmd.Flags().String(outputFileFlag, "", "Writes output to provided file instead of printing to console")
}
func parseInput(p *print.Printer, cmd *cobra.Command, inputArgs []string) (*inputModel, error) {
urlString := inputArgs[0]
requestMethod := flags.FlagToStringValue(p, cmd, requestMethodFlag)
if requestMethod == "" {
requestMethod = http.MethodGet
}
model := inputModel{
URL: urlString,
RequestMethod: strings.ToUpper(requestMethod),
Headers: flags.FlagToStringSliceValue(p, cmd, headerFlag),
Data: flags.FlagToStringPointer(p, cmd, dataFlag),
IncludeResponseHeaders: flags.FlagToBoolValue(p, cmd, includeResponseHeadersFlag),
FailOnHTTPError: flags.FlagToBoolValue(p, cmd, failOnHTTPErrorFlag),
OutputFile: flags.FlagToStringPointer(p, cmd, outputFileFlag),
}
if p.IsVerbosityDebug() {
modelStr, err := print.BuildDebugStrFromInputModel(model)
if err != nil {
p.Debug(print.ErrorLevel, "convert model to string for debugging: %v", err)
} else {
p.Debug(print.DebugLevel, "parsed input values: %s", modelStr)
}
}
return &model, nil
}
func getBearerToken(p *print.Printer) (string, error) {
_, err := auth.AuthenticationConfig(p, auth.AuthorizeUser)
if err != nil {
p.Debug(print.ErrorLevel, "configure authentication: %v", err)
return "", &errors.AuthError{}
}
token, err := auth.GetAuthField(auth.ACCESS_TOKEN)
if err != nil {
return "", fmt.Errorf("get access token: %w", err)
}
return token, nil
}
func buildRequest(model *inputModel, bearerToken string) (*http.Request, error) {
var body io.Reader = http.NoBody
if model.Data != nil {
body = bytes.NewBufferString(*model.Data)
}
req, err := http.NewRequest(model.RequestMethod, model.URL, body)
if err != nil {
return nil, fmt.Errorf("create request: %w", err)
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", bearerToken))
for _, header := range model.Headers {
headerSplit := strings.SplitN(header, ": ", 2)
if len(headerSplit) != 2 {
return nil, fmt.Errorf("badly formatted header %q", header)
}
req.Header.Set(headerSplit[0], headerSplit[1])
}
return req, nil
}
func outputResponse(p *print.Printer, model *inputModel, resp *http.Response) error {
output := make([]byte, 0)
if model.IncludeResponseHeaders {
respHeader, err := httputil.DumpResponse(resp, false)
if err != nil {
return fmt.Errorf("print response headers: %w", err)
}
output = append(output, respHeader...)
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("read response body: %w", err)
}
output = append(output, respBody...)
if model.OutputFile == nil {
p.Outputln(string(output))
} else {
err = os.WriteFile(*model.OutputFile, output, 0o600)
if err != nil {
return fmt.Errorf("write output to file: %w", err)
}
}
return nil
}