1
0
mirror of https://github.com/axllent/mailpit.git synced 2026-04-26 21:12:33 +02:00
Files
mailpit/server/webhook/webhook.go
T
Ralph Slooten f99d9ecf69 Chore: Refactor error handling and resource management across multiple files (golangci-lint)
- Updated error handling to use the error return value for resource closures in tests and functions, ensuring proper error reporting.
- Replaced direct calls to `Close()` with deferred functions that handle errors gracefully.
- Improved readability by using `strings.ReplaceAll` instead of `strings.Replace` for string manipulation.
- Enhanced network connection handling by adding default cases for unsupported network types.
- Updated HTTP response handling to use the appropriate status codes and error messages.
- Removed unused variables and commented-out code to clean up the codebase.
2025-06-22 15:25:21 +12:00

77 lines
1.6 KiB
Go

// Package webhook will optionally call a preconfigured endpoint
package webhook
import (
"bytes"
"encoding/json"
"net/http"
"time"
"github.com/axllent/mailpit/config"
"github.com/axllent/mailpit/internal/logger"
"golang.org/x/time/rate"
)
var (
// RateLimit is the minimum number of seconds between requests
RateLimit = 1
rl rate.Sometimes
rateLimiterSet bool
)
// Send will post the MessageSummary to a webhook (if configured)
func Send(msg any) {
if config.WebhookURL == "" {
return
}
if !rateLimiterSet {
if RateLimit > 0 {
rl = rate.Sometimes{Interval: time.Duration(RateLimit) * time.Second}
} else {
// run 1000 per second - ie: do not limit
rl = rate.Sometimes{First: 1000, Interval: time.Second}
}
rateLimiterSet = true
}
go func() {
rl.Do(func() {
b, err := json.Marshal(msg)
if err != nil {
logger.Log().Errorf("[webhook] invalid data: %s", err.Error())
return
}
req, err := http.NewRequest("POST", config.WebhookURL, bytes.NewBuffer(b))
if err != nil {
logger.Log().Errorf("[webhook] error: %s", err.Error())
return
}
req.Header.Set("User-Agent", "Mailpit/"+config.Version)
req.Header.Set("Content-Type", "application/json")
if config.Label != "" {
req.Header.Set("Mailpit-Label", config.Label)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
logger.Log().Errorf("[webhook] error sending data: %s", err.Error())
return
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
logger.Log().Warnf("[webhook] %s returned a %d status", config.WebhookURL, resp.StatusCode)
return
}
_ = resp.Body.Close()
})
}()
}