Skip to content

Commit

Permalink
feat: improve error handling and configuration in HTTP dispatch
Browse files Browse the repository at this point in the history
- 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 <[email protected]>
  • Loading branch information
appleboy committed Dec 12, 2024
1 parent e66b985 commit b0851f7
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
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

0 comments on commit b0851f7

Please sign in to comment.