GO获取api 接口json格式数据代码

栏目: 后端 · 前端 · 发布时间: 6年前

内容简介:1.接口数据格式;2.go 处理api json 流程;

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"
}

GO获取api 接口json格式数据代码

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:}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

图形程序开发人员指南

图形程序开发人员指南

Michael Abrash / 前导工作室 / 机械工业出版社 / 1998 / 128

Michael Abrash's classic Graphics Programming Black Book is a compilation of Michael's previous writings on assembly language and graphics programming (including from his "Graphics Programming" column......一起来看看 《图形程序开发人员指南》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具