Golang 消费 Restful Api
本文介绍如何使用http包调用Restful API并解析返回内容至struct。
1. 概述
Golang使用http包调用Restful API,http给服务器发送请求并获得响应,响应格式可能为JSON、XML。我们这里使用json类型作为返回值。为了演示这里使用http://dummy.restapiexample.com/api/v1/employees
地址作为API,其返回员工列表信息,读者可以使用Postman进行测试:
{
"status": "success",
"data": [
{
"id": "1",
"employee_name": "Tiger Nixon",
"employee_salary": "320800",
"employee_age": "61",
"profile_image": ""
},
{
"id": "2",
"employee_name": "Garrett Winters",
"employee_salary": "170750",
"employee_age": "63",
"profile_image": ""
},
...
]
}
为了节省篇幅,上面仅列出两条数据。我们的任务就是如何调用API并解析返回内容。
2. 示例实现
2.1. 定义数据结构
我们看到返回数据包括两个部分,status和data,其中data是数组,每个元素表示员工符合类型,因此我们定义两个结构体描述返回值信息。
type EmpType 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"`
}
type RespData struct {
Status string `json:"status"`
Data [] EmpType `json:"data"`
}
EmpType描述员工信息,RespData描述返回值信息,其中包括EmpType数组。结构体定义需和返回JSON内容结构一致,否则会提示cannot unmarshal object into Go value of type
解析异常。
2.2. 调用API
url := "http://dummy.restapiexample.com/api/v1/employees"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
fmt.Println("Error is req: ", err)
}
// create a Client
client := &http.Client{}
// Do sends an HTTP request and
resp, err := client.Do(req)
if err != nil {
fmt.Println("error in send req: ", err)
}
// Defer the closing of the body
defer resp.Body.Close()
http.NewRequest
定义请求,client.Do(req)
执行请求。
2.3. 解析返回数据
// Fill the data with the data from the JSON
var data RespData
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
fmt.Println(err)
}
for _,emp := range data.Data {
fmt.Println(emp)
}
json.NewDecoder(resp.Body).Decode(&data)
解析json内容至结构体。最后依次输出。
3. 总结
本文通过简单示例介绍如何通过http调用Restful API,并解析返回内容。需要提醒的是定义的结构体需和返回内容结构保持一致。
本文参考链接:https://blog.csdn.net/neweastsun/article/details/106212824