Skip to content

Commit a8db3db

Browse files
committed
refactor: Create HTTP request
1 parent 5c1dd8c commit a8db3db

File tree

1 file changed

+15
-11
lines changed

1 file changed

+15
-11
lines changed

main.go

+15-11
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package main
22

33
import (
44
"bytes"
5+
"context"
56
"fmt"
67
"io"
78
"log"
@@ -52,13 +53,11 @@ func run(cmd *cobra.Command, args []string) {
5253
log.Fatalf("failed to load configuration: %v", err)
5354
}
5455

55-
req, err := http.NewRequestWithContext(ctx, opt.Method, args[0], requestBody(opt.Data))
56+
req, err := request(ctx, args[0])
5657
if err != nil {
5758
log.Fatalf("failed to create HTTP request: %v", err)
5859
}
5960

60-
setHeaders(req, opt.Headers)
61-
6261
resp, err := sigv4.NewHTTPClient(&cfg, opt.Service, nil).Do(req)
6362
if err != nil {
6463
log.Fatalf("failed to HTTP request: %v", err)
@@ -73,19 +72,24 @@ func run(cmd *cobra.Command, args []string) {
7372
fmt.Print(string(b))
7473
}
7574

76-
func requestBody(data string) io.Reader {
77-
if data == "" {
78-
return nil
75+
func request(ctx context.Context, url string) (*http.Request, error) {
76+
var body io.Reader
77+
if d := opt.Data; d != "" {
78+
body = bytes.NewReader([]byte(d))
79+
}
80+
81+
req, err := http.NewRequestWithContext(ctx, opt.Method, url, body)
82+
if err != nil {
83+
return nil, err
7984
}
80-
return bytes.NewReader([]byte(data))
81-
}
8285

83-
func setHeaders(req *http.Request, headers []string) {
84-
for _, h := range headers {
86+
for _, h := range opt.Headers {
8587
a := strings.SplitN(h, ":", 2)
8688
if len(a) != 2 {
87-
continue
89+
return nil, fmt.Errorf("invalid request header [%s]", h)
8890
}
8991
req.Header.Add(strings.TrimSpace(a[0]), strings.TrimSpace(a[1]))
9092
}
93+
94+
return req, nil
9195
}

0 commit comments

Comments
 (0)