Add support for sending a request body to http input (#5074)
This commit is contained in:
@@ -3,6 +3,7 @@ package http
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"strings"
|
||||
@@ -17,17 +18,19 @@ import (
|
||||
)
|
||||
|
||||
type HTTP struct {
|
||||
URLs []string `toml:"urls"`
|
||||
Method string
|
||||
URLs []string `toml:"urls"`
|
||||
Method string `toml:"method"`
|
||||
Body string `toml:"body"`
|
||||
ContentEncoding string `toml:"content_encoding"`
|
||||
|
||||
Headers map[string]string
|
||||
Headers map[string]string `toml:"headers"`
|
||||
|
||||
// HTTP Basic Auth Credentials
|
||||
Username string
|
||||
Password string
|
||||
Username string `toml:"username"`
|
||||
Password string `toml:"password"`
|
||||
tls.ClientConfig
|
||||
|
||||
Timeout internal.Duration
|
||||
Timeout internal.Duration `toml:"timeout"`
|
||||
|
||||
client *http.Client
|
||||
|
||||
@@ -52,6 +55,13 @@ var sampleConfig = `
|
||||
# username = "username"
|
||||
# password = "pa$$word"
|
||||
|
||||
## HTTP entity-body to send with POST/PUT requests.
|
||||
# body = ""
|
||||
|
||||
## HTTP Content-Encoding for write request body, can be set to "gzip" to
|
||||
## compress body or "identity" to apply no encoding.
|
||||
# content_encoding = "identity"
|
||||
|
||||
## Optional TLS Config
|
||||
# tls_ca = "/etc/telegraf/ca.pem"
|
||||
# tls_cert = "/etc/telegraf/cert.pem"
|
||||
@@ -132,11 +142,20 @@ func (h *HTTP) gatherURL(
|
||||
acc telegraf.Accumulator,
|
||||
url string,
|
||||
) error {
|
||||
request, err := http.NewRequest(h.Method, url, nil)
|
||||
body, err := makeRequestBodyReader(h.ContentEncoding, h.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
request, err := http.NewRequest(h.Method, url, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if h.ContentEncoding == "gzip" {
|
||||
request.Header.Set("Content-Encoding", "gzip")
|
||||
}
|
||||
|
||||
for k, v := range h.Headers {
|
||||
if strings.ToLower(k) == "host" {
|
||||
request.Host = v
|
||||
@@ -183,6 +202,18 @@ func (h *HTTP) gatherURL(
|
||||
return nil
|
||||
}
|
||||
|
||||
func makeRequestBodyReader(contentEncoding, body string) (io.Reader, error) {
|
||||
var err error
|
||||
var reader io.Reader = strings.NewReader(body)
|
||||
if contentEncoding == "gzip" {
|
||||
reader, err = internal.CompressWithGzip(reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return reader, nil
|
||||
}
|
||||
|
||||
func init() {
|
||||
inputs.Add("http", func() telegraf.Input {
|
||||
return &HTTP{
|
||||
|
||||
Reference in New Issue
Block a user