1.接口数据格式;
{
"code": 0,
"isAdmin": true,
"data": [{
"id": 2,
"ip": "192.168.54.12",
"desc": "nginx",
"owner": "lops01"
},
{
"id": 5,
"ip": "192.168.77.237",
"desc": "运维测试",
"owner": "ops02"
},
{
"id": 6,
"ip": "192.168.77.82",
"desc": "运维管理",
"owner": "ops03"
},
{
"id": 8,
"ip": "192.168.79.230",
"desc": "服务台测试",
"owner": "ops04"
},
{
"id": 9,
"ip": "192.168.79.123",
"desc": "dev测试",
"owner": "ops05"
},
{
"id": 14,
"ip": "192.168.47.107",
"desc": "测试ansible封装",
"owner": "ops06"
}
],
"columns": [{
"name": "id",
"alias": "唯一标识"
},
{
"name": "ip",
"alias": "授权IP地址"
},
{
"name": "desc",
"alias": "备注说明"
},
{
"name": "owner",
"alias": "使用方"
}
],
"message": "success"
}
2.go 处理api json 流程;
(1).导入json,http,io包
(2).定义api 数据结构体;
(3).发送http请求;
(4).序列化json对象转为定义结构体;
(5).输出转化json结果;
3.处理实例实际代码;
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
//定义api接口数据结构和序列化json字段
type Data struct {
ID int `json:"id"`
IP string `json:"IP"`
DESC string `json:"desc"`
OWNER string `json:"owner"`
}
type CloumnsData struct {
NAME string `json:"name"`
ALIAS string `json:"alias"`
}
type Employee struct {
CODE int `json:"code"`
ISADMIN bool `json:"isadmin"`
DATA []Data `json:"data"`
COLUMNS []CloumnsData `json:"columns"`
MESSGAE string `json:"messgae"`
}
//发送http请求和json 序列化并打印数据结构;
func main() {
url := "http://ops-environment.com/channel/ip/v1"
resp, _ := http.Get(url)
s := Employee{}
body, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
json.Unmarshal([]byte(body), &s)
fmt.Println(fmt.Sprintf("%+v",s))
}
4.api 执行处理结果;
{CODE:0 ISADMIN:true DATA:[{ID:2 IP:192.168.54.12 DESC:nginx OWNER:ops01} {ID:5 IP:192.168.77.237 DESC:运维测试 OWNER:ops02} {ID:6 IP:192.168.77.82 DESC:运维管理 OWNER:ops03} {ID:8 IP:192.168.79.230 DESC:服务台测试 OWNER:ops04} {ID:9 IP:192.168.79.123 DESC:dev测试 OWNER:ops05} {ID:14 IP:192.168.47.107 DESC:测试ansible前端封装 OWNER:ops06}] COLUMNS:[{NAME:id ALIAS:唯一标识} {NAME:ip ALIAS:授权IP地址} {NAME:desc ALIAS:备注说明} {NAME:owner ALIAS:使用方}] MESSGAE:}
转载于:https://blog.51cto.com/breaklinux/2409227