Skip to content

Commit 8f52a38

Browse files
Curl example.
1 parent 3be7f8e commit 8f52a38

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

‎chapter7/listing43/listing43.go‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// Sample program to show how to write a simple version of curl using
2+
// the io.Reader and io.Writer interface support.
3+
package main
4+
5+
import (
6+
"fmt"
7+
"io"
8+
"net/http"
9+
"os"
10+
)
11+
12+
// main is the entry point for the application.
13+
func main() {
14+
// r here is a response, and r.Body is an io.Reader.
15+
r, err := http.Get(os.Args[1])
16+
if err != nil {
17+
fmt.Println(err)
18+
return
19+
}
20+
21+
// Create a file to store the response.
22+
file, err := os.Create(os.Args[2])
23+
if err != nil {
24+
fmt.Println(err)
25+
return
26+
}
27+
defer file.Close()
28+
29+
// Use MultiWriter so we can write to stdout and
30+
// a file on the same write operation.
31+
dest := io.MultiWriter(os.Stdout, file)
32+
33+
// Read the response and write to both destinations.
34+
io.Copy(dest, r.Body)
35+
if err := r.Body.Close(); err != nil {
36+
fmt.Println(err)
37+
}
38+
}

0 commit comments

Comments
 (0)