forked from vbauerster/60-days-of-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
deferred.go
64 lines (60 loc) · 1.87 KB
/
deferred.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
56
57
58
59
60
61
62
63
64
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
)
// HTTPBin represents the body returned by GET request in https://httpbin.org/get
type HTTPBin struct {
Args struct {
} `json:"args"`
Headers struct {
Accept string `json:"Accept"`
AcceptEncoding string `json:"Accept-Encoding"`
AcceptLanguage string `json:"Accept-Language"`
Cookie string `json:"Cookie"`
Host string `json:"Host"`
Referer string `json:"Referer"`
SaveData string `json:"Save-Data"`
UpgradeInsecureRequests string `json:"Upgrade-Insecure-Requests"`
UserAgent string `json:"User-Agent"`
} `json:"headers"`
Origin string `json:"origin"`
URL string `json:"url"`
}
func main() {
// interesting link about "What could happen if I don't close response.Body in golang?"
// http://stackoverflow.com/questions/33238518/what-could-happen-if-i-dont-close-response-body-in-golang
// the same is applied with files
// Create a file at tmp directory
f, err := os.Create("/tmp/dat2")
if err != nil {
log.Fatal(err)
}
// the action of close file is deferred(run after function finnish)
defer f.Close()
// write some content(remember that file is open until the end of this function)
f.WriteString("some content")
// performs a http request
resp, err := http.Get("https://httpbin.org/get")
if err != nil {
log.Fatal(err)
}
var bodyMap HTTPBin
// read the body and decode the content
err = json.NewDecoder(resp.Body).Decode(&bodyMap)
// don't forget to close the body
defer resp.Body.Close()
if err != nil {
log.Fatal(err)
}
fmt.Printf("bodyMap.Origin = %+v\n", bodyMap.Origin)
fmt.Printf("bodyMap.URL = %+v\n", bodyMap.URL)
// Is like a Stack, Last in, First out
defer fmt.Println("4")
defer fmt.Println("3")
defer fmt.Println("2")
defer fmt.Println("1")
}