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

webhook: Log HTTP response in case of an error #271

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
19 changes: 16 additions & 3 deletions cmd/channels/webhook/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"github.com/icinga/icinga-notifications/pkg/plugin"
"io"
"net/http"
"os"
"slices"
"strconv"
"strings"
Expand Down Expand Up @@ -142,7 +143,7 @@ func (ch *Webhook) SetConfig(jsonStr json.RawMessage) error {
}

func (ch *Webhook) SendNotification(req *plugin.NotificationRequest) error {
var urlBuff, reqBodyBuff bytes.Buffer
var urlBuff, reqBodyBuff, respBuffer bytes.Buffer
if err := ch.tmplUrl.Execute(&urlBuff, req); err != nil {
return fmt.Errorf("cannot execute URL template: %w", err)
}
Expand All @@ -158,10 +159,22 @@ func (ch *Webhook) SendNotification(req *plugin.NotificationRequest) error {
if err != nil {
return err
}
_, _ = io.Copy(io.Discard, httpResp.Body)
_ = httpResp.Body.Close()

defer func() {
_, _ = io.Copy(io.Discard, httpResp.Body)
_ = httpResp.Body.Close()
}()

// Limit response to 1 MiB as it will be logged in case of an unexpected status code.
limitedRespReader := io.LimitReader(httpResp.Body, 1024*1024)
if _, err := io.Copy(&respBuffer, limitedRespReader); err != nil {
return fmt.Errorf("cannot read response: %w", err)
}

if !slices.Contains(ch.respStatusCodes, httpResp.StatusCode) {
_, _ = fmt.Fprintf(os.Stderr, "received unexpected HTTP response code %d with body %q\n",
httpResp.StatusCode, respBuffer.String())

return fmt.Errorf("unaccepted HTTP response status code %d not in %v",
httpResp.StatusCode, ch.respStatusCodes)
}
Expand Down
Loading