Merge pull request #70 from aierui/request_method

feat: Support configure request method
This commit is contained in:
Nikolay 2024-06-24 09:37:00 +02:00 committed by GitHub
commit d5fb341414
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

17
push.go
View File

@ -32,6 +32,10 @@ type PushOptions struct {
// By default the compression is enabled.
DisableCompression bool
// Method is an optional of HTTP request method.
// By default the Method is GET.
Method string
// Optional WaitGroup for waiting until all the push workers created with this WaitGroup are stopped.
WaitGroup *sync.WaitGroup
}
@ -264,6 +268,7 @@ func PushMetricsExt(ctx context.Context, pushURL string, writeMetrics func(w io.
type pushContext struct {
pushURL *url.URL
method string
pushURLRedacted string
extraLabels string
headers http.Header
@ -295,6 +300,11 @@ func newPushContext(pushURL string, opts *PushOptions) (*pushContext, error) {
return nil, fmt.Errorf("missing host in pushURL=%q", pushURL)
}
method := opts.Method
if len(method) == 0 {
method = http.MethodGet
}
// validate ExtraLabels
extraLabels := opts.ExtraLabels
if err := validateTags(extraLabels); err != nil {
@ -317,6 +327,7 @@ func newPushContext(pushURL string, opts *PushOptions) (*pushContext, error) {
client := &http.Client{}
return &pushContext{
pushURL: pu,
method: method,
pushURLRedacted: pushURLRedacted,
extraLabels: extraLabels,
headers: headers,
@ -367,18 +378,18 @@ func (pc *pushContext) pushMetrics(ctx context.Context, writeMetrics func(w io.W
// Prepare the request to sent to pc.pushURL
reqBody := bytes.NewReader(bb.B)
req, err := http.NewRequestWithContext(ctx, "GET", pc.pushURL.String(), reqBody)
req, err := http.NewRequestWithContext(ctx, pc.method, pc.pushURL.String(), reqBody)
if err != nil {
panic(fmt.Errorf("BUG: metrics.push: cannot initialize request for metrics push to %q: %w", pc.pushURLRedacted, err))
}
// Set the needed headers
req.Header.Set("Content-Type", "text/plain")
// Set the needed headers, and `Content-Type` allowed be overwrited.
for name, values := range pc.headers {
for _, value := range values {
req.Header.Add(name, value)
}
}
req.Header.Set("Content-Type", "text/plain")
if !pc.disableCompression {
req.Header.Set("Content-Encoding", "gzip")
}