48 lines
1019 B
Go
48 lines
1019 B
Go
package simplelog
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/url"
|
|
)
|
|
|
|
type WebhookHandler struct {
|
|
webhookURL string
|
|
}
|
|
|
|
func (w *WebhookHandler) Enabled(ctx context.Context, level slog.Level) bool {
|
|
return true
|
|
}
|
|
|
|
func (w *WebhookHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
|
return w
|
|
}
|
|
|
|
func (w *WebhookHandler) WithGroup(name string) slog.Handler {
|
|
return w
|
|
}
|
|
|
|
func NewWebhookHandler(webhookURL string) (*WebhookHandler, error) {
|
|
if _, err := url.ParseRequestURI(webhookURL); err != nil {
|
|
return nil, fmt.Errorf("invalid webhook URL: %v", err)
|
|
}
|
|
return &WebhookHandler{webhookURL: webhookURL}, nil
|
|
}
|
|
|
|
func (w *WebhookHandler) Handle(ctx context.Context, record slog.Record) error {
|
|
jsonData, err := json.Marshal(record)
|
|
if err != nil {
|
|
return fmt.Errorf("error marshaling event: %v", err)
|
|
}
|
|
response, err := http.Post(w.webhookURL, "application/json", bytes.NewBuffer(jsonData))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer response.Body.Close()
|
|
return nil
|
|
}
|