-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
57 lines (50 loc) · 1001 Bytes
/
main.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
)
type person struct {
Name string `json:"name"`
}
type people struct {
Number int `json:"number"`
Person []person `json:"people"`
}
func main() {
apiURL := "http://api.open-notify.org/astros.json"
people, err := getAstros(apiURL)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%d people found in space.\n", people.Number)
for _, p := range people.Person {
fmt.Printf("Let's wave to: %s\n", p.Name)
}
}
func getAstros(apiURL string) (people, error) {
p := people{}
req, err := http.NewRequest(http.MethodGet, apiURL, nil)
if err != nil {
return p, err
}
req.Header.Set("User-Agent", "spacecount-tutorial")
res, err := http.DefaultClient.Do(req)
if err != nil {
return p, err
}
if res.Body != nil {
defer res.Body.Close()
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return p, err
}
err = json.Unmarshal(body, &p)
if err != nil {
return p, err
}
return p, nil
}