共计 2208 个字符,预计需要花费 6 分钟才能阅读完成。
解决理论需要,案例分享。
-
申请 Zabbix API,通过 itemid 获取到 AppName(利用集名称)
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "strings" ) func PostRequest(payload string, url string) { method := "POST" pl := strings.NewReader(payload) client := &http.Client{} req, err := http.NewRequest(method, url, pl) if err != nil {fmt.Println(err) return } req.Header.Add("Content-Type", "application/json") res, err := client.Do(req) if err != nil {fmt.Println(err) return } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil {log.Println(err) return } fmt.Println(string(body)) } func main() { const api = "http://192.168.11.11:28080/api_jsonrpc.php" const token = "a638200c24a8bea7f78cd5cabf3d1dd5" const itemid = "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":2}
-
将响应后果(json)转构造体,不便取值
在原来代码的根底上,持续编码。
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "strings" ) type resultInfo struct { Applicationid string `json:"applicationid"` Hostid string `json:"hostid"` Name string `json:"name"` Flags string `json:"flags"` Templateids []string `json:"templateids"`} type resultArr []resultInfo type Response struct { Jsonrpc string `json:"jsonrpc"` Result resultArr `json:result` Id int `json:"id"` } type Byte []byte func JsonConvertStruct(body Byte) { var response Response json.Unmarshal([]byte(body), &response) fmt.Println(response.Result[0].Name) } func PostRequest(payload string, url string) { method := "POST" pl := strings.NewReader(payload) client := &http.Client{} req, err := http.NewRequest(method, url, pl) if err != nil {fmt.Println(err) return } req.Header.Add("Content-Type", "application/json") res, err := client.Do(req) if err != nil {fmt.Println(err) return } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil {log.Println(err) return } JsonConvertStruct(body) } func main() { const api = "http://192.168.11.11:28080/api_jsonrpc.php" const token = "a638200c24a8bea7f78cd5cabf3d1dd5" const itemid = "33918" a := fmt.Sprintf(`{ "jsonrpc": "2.0", "method": "application.get", "params": {"itemids": "%s"}, "auth": "%s","id": 2 }`, itemid, token) PostRequest(a, api) }
后果:
TEST
-
来自最好的总结
人生苦短,倡议你还是用 python 吧!
本文转载于(喜爱的盆友关注咱们):https://mp.weixin.qq.com/s/mB…
正文完