forked from ardanlabs/gotraining
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exercise1.go
55 lines (44 loc) · 1.28 KB
/
exercise1.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// All material is licensed under the Apache License Version 2.0, January 2004
// http://www.apache.org/licenses/LICENSE-2.0
// http://play.golang.org/p/KtrDN1BStt
// Download any document from the web and display the content in
// the terminal and write it to a file at the same time.
package main
import (
"fmt"
"io"
"net/http"
"os"
)
// main is the entry point for the application.
func main() {
// Retrieve the RSS feed for the blog.
resp, err := http.Get("http://www.goinggo.net/feeds/posts/default")
if err != nil {
fmt.Println(err)
return
}
// Arrange for the response Body to be Closed using defer.
defer resp.Body.Close()
// A slice of io.Writers we will write the file to.
var writers []io.Writer
// Send the document to stdout.
writers = append(writers, os.Stdout)
// Send the document to a file.
file, err := os.Create("goinggo.rss")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
// Send the document to the file.
writers = append(writers, file)
// MultiWriter(io.Writer...) returns a single writer which multiplexes its
// writes across all of the writers we pass in.
dest := io.MultiWriter(writers...)
// Write to dest the same way as before, copying from the Body.
_, err = io.Copy(dest, resp.Body)
if err != nil {
fmt.Println(err)
}
}