Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: improve error handling and configuration in HTTP dispatch #822

Merged
merged 1 commit into from
Dec 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions notify/feedback.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -34,14 +44,16 @@ 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
}

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")
Expand All @@ -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
}
1 change: 1 addition & 0 deletions notify/global.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ var (
MaxIdleConns: 5,
MaxIdleConnsPerHost: 5,
MaxConnsPerHost: 20,
Proxy: http.ProxyFromEnvironment, // Support proxy
}
feedbackClient = &http.Client{
Transport: transport,
Expand Down
Loading