Skip to content

Commit

Permalink
feat: Sending file data
Browse files Browse the repository at this point in the history
  • Loading branch information
rxnew committed Jul 1, 2021
1 parent c00a48b commit 8050591
Showing 1 changed file with 24 additions and 4 deletions.
28 changes: 24 additions & 4 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,12 +73,12 @@ func run(cmd *cobra.Command, args []string) {
}

func request(ctx context.Context, url string) (*http.Request, error) {
var body io.Reader
if d := opt.Data; d != "" {
body = bytes.NewReader([]byte(d))
b, err := requestBody(opt.Data)
if err != nil {
return nil, err
}

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

return req, nil
}

func requestBody(data string) (io.Reader, error) {
if data == "" {
return nil, nil
}

if data[0] == '@' && len(data) > 1 {
b, err := os.ReadFile(data[1:])
if err != nil {
return nil, fmt.Errorf("failed to read file: %w", err)
}
return bytes.NewReader(removeNewline(b)), nil
}

return bytes.NewReader(removeNewline([]byte(data))), nil
}

func removeNewline(b []byte) []byte {
return []byte(strings.NewReplacer("\r\n", "", "\r", "", "\n", "").Replace(string(b)))
}

0 comments on commit 8050591

Please sign in to comment.