Skip to content

Commit 8050591

Browse files
committed
feat: Sending file data
1 parent c00a48b commit 8050591

File tree

1 file changed

+24
-4
lines changed

1 file changed

+24
-4
lines changed

main.go

+24-4
Original file line numberDiff line numberDiff line change
@@ -73,12 +73,12 @@ func run(cmd *cobra.Command, args []string) {
7373
}
7474

7575
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))
76+
b, err := requestBody(opt.Data)
77+
if err != nil {
78+
return nil, err
7979
}
8080

81-
req, err := http.NewRequestWithContext(ctx, opt.Method, url, body)
81+
req, err := http.NewRequestWithContext(ctx, opt.Method, url, b)
8282
if err != nil {
8383
return nil, err
8484
}
@@ -93,3 +93,23 @@ func request(ctx context.Context, url string) (*http.Request, error) {
9393

9494
return req, nil
9595
}
96+
97+
func requestBody(data string) (io.Reader, error) {
98+
if data == "" {
99+
return nil, nil
100+
}
101+
102+
if data[0] == '@' && len(data) > 1 {
103+
b, err := os.ReadFile(data[1:])
104+
if err != nil {
105+
return nil, fmt.Errorf("failed to read file: %w", err)
106+
}
107+
return bytes.NewReader(removeNewline(b)), nil
108+
}
109+
110+
return bytes.NewReader(removeNewline([]byte(data))), nil
111+
}
112+
113+
func removeNewline(b []byte) []byte {
114+
return []byte(strings.NewReplacer("\r\n", "", "\r", "", "\n", "").Replace(string(b)))
115+
}

0 commit comments

Comments
 (0)