核心思路如下:
- 设置header和auth信息,获取http的request,
- 获取api返回的[]byte数据,然后反序列化结构体实例
- 如果api获取的是复杂json数据的话就需要定义map[string]interface{}来接收数据
- 取值赋值给返回结构体实例
package module
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
)
//定义Tapd返回结构体
type Tapd struct {
ID string `json:"id"`
Title string `json:"title"`
Operator string `json:"operator"`
Priority string `json:"priority"`
Status string `json:"status"`
Url string `json:"url"`
}
//定义反序列化结构体结构
type Request struct {
Status int `json:"status"`
Data []Bug `json:"data"`
Info string `json:"info"`
}
//定义序列化Bug字段
type Bug map[string]interface{}
func GetTAPDIssues(url, username, password string) ([]Tapd, int, error) {
//get http client
client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Println("request tapd api failed", err)
}
// set Header and Auth
req.Header.Set("Content-Type", "application/json")
req.SetBasicAuth(username, password)
response, err := client.Do(req)
defer response.Body.Close()
//获取response.Body中的数据,返回是[]byte类型的数据
body, err := ioutil.ReadAll(response.Body)
//创建结构体实例来反序列化json数据
var request Request
err = json.Unmarshal(body, &request)
if err != nil {
return nil, 0, nil
}
//request 中data字段值是interface类型
//需要类型断言成 map[string]interface 类型的数据,以便获取
var data map[string]interface{}
var tapd []Tapd = make([]Tapd, 0)
var temp Tapd
for i, _ := range request.Data {
data = request.Data[i]["Bug"].(map[string]interface{})
if fmt.Sprintf("%v", data["status"]) != "closed" && data["priority"].(string) == "high" || data["priority"].(string) == "urgent" {
temp.ID = data["id"].(string)
temp.Title = data["title"].(string)
temp.Operator = data["current_owner"].(string)
temp.Priority = data["priority"].(string)
temp.Status = data["status"].(string)
tapd = append(tapd, temp)
}
}
return tapd, len(tapd), nil
}
func main() {
username := "xxx"
password := "xxx"
url := `https://api.tapd.cn/bugs?workspace_id=123243454`
tapd, totalTapd, _ := GetTAPDIssues(url, username, password)
fmt.Println("tapd====>", tapd)
fmt.Println("len tapd====>", totalTapd)
}