Golang 消費 Restful Api

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,並解析返回內容。需要提醒的是定義的結構體需和返回內容結構保持一致。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章