Skip to content

Commit

Permalink
Merge pull request #4 from fortio/h2_streaming
Browse files Browse the repository at this point in the history
streaming client mode
  • Loading branch information
ldemailly authored Feb 26, 2023
2 parents 9006ba6 + 5e9b67b commit 9a7b27c
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
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

0 comments on commit 9a7b27c

Please sign in to comment.