要使用Go调用Logstash,需要使用Logstash的REST接口。以下是一个基本的示例:
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
func main() {
url := "http://localhost:9600/_bulk" // Logstash REST API URL
data := `{"index": {"_index": "myindex", "_type": "mytype"}}
{"message": "Hello, world!"}` // JSON data to send to Logstash
req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(data)))
if err != nil {
fmt.Println(err)
return
}
req.Header.Set("Content-Type", "application/json") // Set the request header
client := &http.Client{}
resp, err := client.Do(req) // Send the request
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
fmt.Println(resp.Status)
}
该示例使用http.NewRequest()
创建一个POST请求,并将JSON数据发送到Logstash的REST接口。在发送请求时,我们还设置了请求标头以指定请求正文的类型为JSON。最后,我们使用http.Client.Do()
方法发送请求并获取响应。
当您发送数据到Logstash时,请确保已配置正确的输入插件和过滤器。例如,如果您要将数据发送到Elasticsearch,则您需要使用elasticsearch输出插件。详细信息请参见Logstash官方文档:https://www.elastic.co/guide/en/logstash/current/index.html