<p>Hello, I'm very fresh to Go. What I would consider to be a really quick script in Posh, I'm having a hard time figuring out with Go.</p>
<p>I'm trying to figure out how to interact with my Zabbix server's API. I've included what normal looks like as well.</p>
<pre><code>/* This is a particular post that uses the user.login method
POST http://myserver.mydomain.local/zabbix/api_jsonrpc.php
{
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": "user1",
"password": "Derp"
},
"id": 1,
"auth": null
}
Json Response
{
"jsonrpc": "2.0",
"result": "9433bae6b19c1fe84a2a75ed53d4622d",
"id": 1
}
*/
package main
import (
"fmt"
"encoding/json"
"net/http"
"bytes"
"io/ioutil"
)
type LoginPost struct {
JSONrpc string `json:"jsonrpc"`
Method string `json:"method"`
ID int64 `json:"id"`
Params struct {
User string `json:"user"`
Password string `json:"password"`
} `json:"params"`
}
func main() {
url := "http://myserver.mydomain.local/zabbix/api_jsonrpc.php"
username := "user1"
password := "Derp"
login := &LoginPost{ // Build my POST struct
JSONrpc: "2.0",
Method: "user.login",
ID: 1,
}
login.Params.User = username
login.Params.Password = password
loginJSON, _ := json.Marshal(login) // Convert my login struct to JSON format
fmt.Println(string(loginJSON)) // Check that my JSON looks good
// OUTPUT
// {"jsonrpc":"2.0","method":"user.login","id":1,"params":{"user":"user1","password":"Derp"}}
b := new(bytes.Buffer) // initialize b, my body,
json.NewEncoder(b).Encode(string(loginJSON)) // This piece converts it to an io.Reader type
res, _ := http.Post(url, "application/json", b) // Make the actual call
// fmt.Println(res) // See the Raw Response
body, _ := ioutil.ReadAll(res.Body) // convert to bytes
// fmt.Println(body) // see the byte array
fmt.Println(string(body)) // View the reply in readable JSON format
// OUTPUT
// {"jsonrpc":"2.0","error":{"code":-32600,"message":"Invalid Request.","data":"JSON-rpc version is not specified."},"id":null}
}
</code></pre>
<p>Looking up this error, <a href="https://www.zabbix.com/forum/showthread.php?t=53140" rel="nofollow">https://www.zabbix.com/forum/showthread.php?t=53140</a>, it looks like this happens when the server is expecting different input. Can I send it as a string rather than the io.Reader stream? I know I'm clearly misunderstanding this. I'm trying to figure out where. I'm looking at several guides, and people seem to go about the same thing in so many ways it seems like they're almost conflicting. Any advice or guides would be appreciated.</p>
<p>Edit: I found this guy's package for zabbix. I'll use it as a reference to understand what I've been doing wrong. <a href="https://github.com/AlekSi/zabbix" rel="nofollow">https://github.com/AlekSi/zabbix</a></p>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传