-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
53 lines (46 loc) · 1.25 KB
/
main.go
File metadata and controls
53 lines (46 loc) · 1.25 KB
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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type Response struct {
Page int `json:"page"`
PerPage int `json:"per_page"`
Total int `json:"total"`
TotalPages int `json:"total_pages"`
Data []struct {
ID int `json:"id"`
Email string `json:"email"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Avatar string `json:"avatar"`
} `json:"data"`
Support struct {
URL string `json:"url"`
Text string `json:"text"`
} `json:"support"`
}
func main() {
resp, err := http.Get("https://reqres.in/api/users?page=2")
if err != nil {
fmt.Println("No response from request")
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body) // response body is []byte
var result Response
if err := json.Unmarshal(body, &result); err != nil { // Unmarshal will parse the []byte to the go struct pointer with type Response
fmt.Println("Can not unmarshal JSON")
}
// fmt.Println(PrettyPrint(result))
// Loop throush the data node for the FirstName
for _, rec := range result.Data {
fmt.Println(rec.FirstName)
}
}
// PrettyPrint to print struct in a readable way
func PrettyPrint(i interface{}) string {
s, _ := json.MarshalIndent(i, "", "\t")
return string(s)
}