From a19eef4c81452413908c423a179d4b2867aa4db6 Mon Sep 17 00:00:00 2001 From: Bo-Yi Wu Date: Thu, 12 Dec 2024 16:56:44 +0800 Subject: [PATCH] feat: improve error handling and configuration in HTTP dispatch (#822) - Enhance `DispatchFeedback` function documentation with detailed parameters and return values - Add context timeout handling in `DispatchFeedback` function - Trim header values before setting them in the request - Add error handling for non-OK HTTP response status in `DispatchFeedback` - Support proxy configuration from the environment in `global.go` Signed-off-by: Bo-Yi Wu --- notify/feedback.go | 20 ++++++++++++++++++-- notify/global.go | 1 + 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/notify/feedback.go b/notify/feedback.go index bae039316..9d2a64432 100644 --- a/notify/feedback.go +++ b/notify/feedback.go @@ -23,7 +23,17 @@ func extractHeaders(headers []string) map[string]string { return result } -// DispatchFeedback sends a feedback to the configured gateway. +// DispatchFeedback sends a feedback log entry to a specified URL via an HTTP POST request. +// +// Parameters: +// - ctx: The context for the HTTP request. +// - log: The log entry to be sent as feedback. +// - url: The destination URL for the feedback. +// - timeout: The timeout duration for the HTTP request in seconds. +// - header: A slice of strings representing additional headers to be included in the request. +// +// Returns: +// - error: An error if the request fails or the response status is not OK. func DispatchFeedback(ctx context.Context, log logx.LogPushEntry, url string, timeout int64, header []string) error { if url == "" { return errors.New("url can't be empty") @@ -34,6 +44,8 @@ func DispatchFeedback(ctx context.Context, log logx.LogPushEntry, url string, ti return err } + ctx, cancel := context.WithTimeout(ctx, time.Duration(timeout)*time.Second) + defer cancel() req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(payload)) if err != nil { return err @@ -41,7 +53,7 @@ func DispatchFeedback(ctx context.Context, log logx.LogPushEntry, url string, ti headers := extractHeaders(header) for k, v := range headers { - req.Header.Set(k, v) + req.Header.Set(k, strings.TrimSpace(v)) } req.Header.Set("Content-Type", "application/json; charset=utf-8") @@ -57,5 +69,9 @@ func DispatchFeedback(ctx context.Context, log logx.LogPushEntry, url string, ti return err } + if resp.StatusCode != http.StatusOK { + return errors.New("failed to send feedback") + } + return nil } diff --git a/notify/global.go b/notify/global.go index c4d8ae56b..88eec445c 100644 --- a/notify/global.go +++ b/notify/global.go @@ -28,6 +28,7 @@ var ( MaxIdleConns: 5, MaxIdleConnsPerHost: 5, MaxConnsPerHost: 20, + Proxy: http.ProxyFromEnvironment, // Support proxy } feedbackClient = &http.Client{ Transport: transport,