Skip to content
This repository was archived by the owner on Jul 14, 2022. It is now read-only.

Commit 84d9335

Browse files
authored
Merge pull request #42 from gbmor-forks/stdin-request-body
Request body from stdin
2 parents 9209801 + 2fcfc51 commit 84d9335

2 files changed

Lines changed: 38 additions & 2 deletions

File tree

README.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,3 +122,22 @@ _(optional)_
122122
|`html`|`text/html`|
123123
|`xml`|`application/xml`|
124124
|`plain`|`text/plain`|
125+
126+
### Providing a Request Body via stdin
127+
128+
In addition to `-b`/`--body`, you may provide a request body via stdin.
129+
If you combine this method with the `-b` flag, the body provided with `-b` will be ignored.
130+
131+
**Example with Pipes**
132+
```shell
133+
$ echo '{"foo":"bar"}' | hopp-cli post -c js http://example.com
134+
```
135+
**Example with Redirection**
136+
```shell
137+
$ cat myrequest.json
138+
{
139+
"foo": "bar"
140+
}
141+
142+
$ hopp-cli post -c js http://example.com <myrequest.json
143+
```

methods/basic.go

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@ package methods
33
import (
44
"bytes"
55
"fmt"
6+
"io"
67
"net/http"
8+
"os"
79

810
"github.com/urfave/cli"
911
)
@@ -15,8 +17,23 @@ func BasicRequestWithBody(c *cli.Context, method string) (string, error) {
1517
return "", err
1618
}
1719

18-
var jsonStr = []byte(c.String("body"))
19-
req, err := http.NewRequest(method, url, bytes.NewBuffer(jsonStr))
20+
// Check if we're being passed a request body from stdin.
21+
// If so, use that. Otherwise, use the request data passed via cli flag.
22+
var body []byte
23+
stat, err := os.Stdin.Stat()
24+
if err != nil {
25+
return "", fmt.Errorf("error getting file info for stdin fd: %w", err)
26+
}
27+
if (stat.Mode() & os.ModeCharDevice) == 0 {
28+
body, err = io.ReadAll(os.Stdin)
29+
if err != nil {
30+
return "", fmt.Errorf("error reading from stdin: %w", err)
31+
}
32+
} else {
33+
body = []byte(c.String("body"))
34+
}
35+
36+
req, err := http.NewRequest(method, url, bytes.NewBuffer(body))
2037
if err != nil {
2138
return "", fmt.Errorf("Error creating request: %s", err.Error())
2239
}

0 commit comments

Comments
 (0)