解决实际需求,案例分享。
1.请求Zabbix API,通过itemid获取到AppName(应用集名称)
packagemain import( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "strings" ) funcPostRequest(payloadstring,urlstring){ method:="POST" pl:=strings.NewReader(payload) client:=&http.Client{} req,err:=http.NewRequest(method,url,pl) iferr!=nil{ fmt.Println(err) return } req.Header.Add("Content-Type","application/json") res,err:=client.Do(req) iferr!=nil{ fmt.Println(err) return } deferres.Body.Close() body,err:=ioutipythonl.ReadAll(res.Body) iferr!=nil{ log.Println(err) return } fmt.Println(string(body)) } funcmain(){ constapi="http://192.168.11.11:28080/api_jsonrpc.php" consttoken="a638200c24a8bea7f78cd5cabf3d1dd5" constitemid="33918" a:=fmt.Sprintf(`{ "jsonrpc":"2.0", "method":"application.get", "params":{"itemids":"%s"}, "auth":"%s","id":2 }`,itemid,token) PostRequest(a,api) }
响应结果:
{"jsonrpc":"2.0","result":[{"applicationid":"1574","hostid":"10354","name":"TEST","flags":"0","templateids":[]}],"id":python2}
2.将响应结果(json)转结构体,方便取值
在原来代码的基础上,继续编码。
packagemain import( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "strings" ) typeresultInfostruct{ Applicationidstring`json:"applicationid"` Hostidstring`json:"hostid"` Namesjstring`json:"name"` Flagsstring`json:"flags"` Templateids[]string`json:"templateids"` } typeresultArr[]resultInfo typeResponsestruct{ Jsonrpcstring`json:"jsonrpc"` ResultresultArr`json:result` Idint`json:"id"` } typeByte[]byte funcJsonConvertStruct(bodyByte){ varresponseResponse json.Unmarshal(编程客栈[]byte(body),&response) fmt.Println(response.Result[0].Name) } funcPostRequest(payloadstr开发者_JAVAing,urlstring){ method:="POST" pl:=strings.NewReader(payload) client:=&http.Client{} req,err:=http.NewRequest(method,url,pl) iferr!=nil{ fmt.Println(err) return } req.Header.Add("Content-Type","application/json") res,err:=client.Do(req) iferr!=nil{ fmt.Println(err) return } deferres.Body.Close() body,err:=ioutil.ReadAll(res.Body) iferr!=nil{ log.Println(err) return } JsonConvertStruct(body) } funcmain(){ constapi="http://192.168.11.11:28080/api_jsonrpc.php" consttoken="a638200c24a8bea7f78cd5cabf3d1dd5" constitemid="33918" a:=fmt.Sprintf(`{ "jsonrpc":"2.0", "method":"application.get", "params":{"itemids":"%s"}, "auth":"%s","id":2 }`,itemid,token) PostRequestjs(a,api) }
结果:
TEST
3.来自最好的总结
人生苦短,建议你还是用python吧!
到此这篇关于golang实现Json转结构体的示例详解的文章就介绍到这了,更多相关Golang Json转结构体内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
精彩评论