-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapi.go
112 lines (85 loc) · 2.99 KB
/
api.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
)
const (
url = "http://dummy.restapiexample.com/api/v1/employees"
)
// Employee is the structure which contains the details of an employee
type Employee struct {
ID string `json:"id"`
EmployeeName string `json:"employee_name"`
EmployeeSalary string `json:"employee_salary"`
EmployeeAge string `json:"employee_age"`
ProfileImage string `json:"profile_image"`
}
// EmployeeResponse structure mirrors the JSON response from the endpoint
type EmployeeResponse struct {
Status string `json:"status"`
Data []Employee `json:"data"`
}
// CallAPI method calls a sample REST API will returns JSON response
func CallAPI() {
resp, err := http.Get(url)
if err != nil {
// Some error occured
log.Panicln(err)
}
defer resp.Body.Close()
unStructuredJSON(resp)
structuredJSON(resp)
}
// structuredJSON method parses the structured JSON returned from the response
// Decode JSON data to struct
// Structure of JSON data can be found here: http://dummy.restapiexample.com/api/v1/employees
func structuredJSON(resp *http.Response) {
// // Method 1: [not ideal] Using ioutil.ReadAll
// var employeeResponse EmployeeResponse
// body, err := ioutil.ReadAll(resp.Body)
// if err != nil {
// fmt.Println(err)
// }
// json.Unmarshal([]byte(body), &employeeResponse)
// fmt.Println("Status = ", employeeResponse.Data[0].EmployeeName)
// Method 2: [Ideal way] Using NewDecoder
var response EmployeeResponse
if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
log.Fatalln(err)
}
for _, employee := range response.Data {
fmt.Printf("Name: %s\t\tSalary: %s\n", employee.EmployeeName, employee.EmployeeSalary)
}
}
// unStructuredJSON method parses the unstructured JSON returned from the response
// Create a Map to store the JSON response
// Use "json.Unmarshal" and "type assertion" to read the reponse
func unStructuredJSON(resp *http.Response) {
// Output: array of map[employee_age:61 employee_name:Tiger Nixon employee_salary:320800 id:1 profile_image:]
// Type: []interface {}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
}
// Returns the status of the response
fmt.Printf("Response Status = %s\n", resp.Status)
var result map[string]interface{}
json.Unmarshal([]byte(body), &result)
status := result["status"]
fmt.Println("Response Status: ", status)
// Output: array of map[employee_age:61 employee_name:Tiger Nixon employee_salary:320800 id:1 profile_image:]
// Type: []interface {}
data := result["data"]
// Use Type assertion to fetch the value of data
for _, employee := range data.([]interface{}) {
// Output: map[employee_age:64 employee_name:Paul Byrd employee_salary:725000 id:17 profile_image:]
// Type: map[string]interface{}
// fmt.Println(employee)
// Print Employee name and salary
details := employee.(map[string]interface{})
fmt.Printf("Name: %s\t\tSalary: %s\n", details["employee_name"], details["employee_salary"])
}
}