-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
65 lines (46 loc) · 980 Bytes
/
main.go
File metadata and controls
65 lines (46 loc) · 980 Bytes
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
65
/*
Astronauts. Some are in space. Program using API to check how many are there.
*/
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
)
type persons struct {
Number int `json:"number"`
}
func main() {
url := "http://api.open-notify.org/astros" // API endpoint
client := http.Client{ // HTTP client
Timeout: time.Second * 2,
}
fetch(url, client)
}
func fetch(url string, client http.Client) {
req, err := http.NewRequest("GET", url, nil) // Request
if err != nil {
log.Fatal(err)
}
req.Header.Set("User-Agent", "api-testing")
res, err := client.Do(req) // Fire request
if err != nil {
log.Fatal(err)
}
parse(*res)
}
func parse(res http.Response) {
body, err := ioutil.ReadAll(res.Body) // Get body out of resource
if err != nil {
log.Fatal(err)
}
persons1 := persons{}
parsed := json.Unmarshal(body, &persons1) // JSON parse
if parsed != nil {
log.Fatal(parsed)
}
fmt.Println(persons1.Number)
}