Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

streaming client mode #4

Merged
merged 1 commit into from
Feb 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,3 +136,16 @@ User-Agent: Go-http-client/2.0

body:
```

### Streaming mode:

First prints foo, then bar after 3 second:
(assumes fortio server including https://github.com/fortio/fortio/pull/721 ie 1.53+)

```
(echo "foo"; sleep 3; echo "bar") | go run . -stream -url localhost:8080
15:53:30 I h2c GET on http://localhost:8080
foo
bar
15:53:33 I Response code 200, proto HTTP/2.0, size 8
```
22 changes: 21 additions & 1 deletion h2cli.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
// Copyright 2023 Fortio Authors
// License: Apache 2.0
//
// Feel free to inspire (copy) from this code but linking back to
// https://github.com/fortio would be appreciated.

package main

import (
Expand All @@ -23,6 +29,7 @@ var (
method = flag.String("method", "GET", "HTTP method to use")
caCert = flag.String("cacert", "",
"`Path` to a custom CA certificate file instead standard internet/system CAs")
stream = flag.Bool("stream", false, "stream stdin to server and back (h2 mode only)")
)

func main() {
Expand Down Expand Up @@ -72,14 +79,27 @@ func main() {
}
log.Infof("%s%s on %s", h2c, *method, *urlFlag)
// Perform the request
req, err := http.NewRequestWithContext(context.Background(), *method, *urlFlag, nil)
var bodyReader io.Reader
if *stream {
bodyReader = os.Stdin
}
req, err := http.NewRequestWithContext(context.Background(), *method, *urlFlag, bodyReader)
if err != nil {
log.Fatalf("Request method %q url %q error: %v", *method, *urlFlag, err)
}
resp, err := client.Do(req)
if err != nil {
log.Fatalf("Failed %q %q - error: %v", *method, *urlFlag, err)
}
if *stream {
n, err := io.Copy(os.Stdout, resp.Body)
log.Infof("Response code %d, proto %s, size %d", resp.StatusCode, resp.Proto, n)
if err != nil {
log.Fatalf("Error copying response body: %v", err)
}
return
}
// else, traditional read all reply mode
body, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
Expand Down