From 65c5e7e815034587bf7bf73dcf2945bceef6f0f6 Mon Sep 17 00:00:00 2001 From: Chris Dzombak Date: Sun, 7 Jan 2024 18:02:44 -0500 Subject: [PATCH] set user-agent header for success notification webhooks --- deliver.go | 28 +++++++++++++++++++++++++--- main.go | 15 ++------------- 2 files changed, 27 insertions(+), 16 deletions(-) diff --git a/deliver.go b/deliver.go index 90893b5..313f2e9 100644 --- a/deliver.go +++ b/deliver.go @@ -48,9 +48,12 @@ type discordDeliveryConfig struct { logFileName string } -const ntfyTimeout = 10 * time.Second -const discordTimeout = 10 * time.Second -const mailTimeout = 10 * time.Second +const ( + successNotifyTimeout = 10 * time.Second + ntfyTimeout = 10 * time.Second + discordTimeout = 10 * time.Second + mailTimeout = 10 * time.Second +) func executeDeliveries(config *deliveryConfig, runOutput *runOutput) []error { var deliveryErrors []error @@ -168,6 +171,25 @@ func executeDiscordDelivery(cfg *discordDeliveryConfig, runOutput *runOutput) er return nil } +func deliverSuccessNotification(url string) error { + client := http.DefaultClient + client.Timeout = successNotifyTimeout + req, err := http.NewRequest(http.MethodGet, url, nil) + if err != nil { + return fmt.Errorf("failed to build GET request for '%s': %w", url, err) + } + req.Header.Set("User-Agent", productIdentifier()) + resp, err := client.Do(req) + if err != nil { + return fmt.Errorf("failed to GET '%s': %w", url, err) + } + defer resp.Body.Close() + if resp.StatusCode > 200 || resp.StatusCode < 299 { + return fmt.Errorf("failed to GET '%s' (%s)", url, resp.Status) + } + return nil +} + func extendErrSlice(errs []error, err error) []error { if err != nil { errs = append(errs, err) diff --git a/main.go b/main.go index 1a4265c..c3ea822 100644 --- a/main.go +++ b/main.go @@ -4,7 +4,6 @@ import ( "flag" "fmt" "log" - "net/http" "net/url" "os" "os/user" @@ -64,8 +63,6 @@ const ( CensorEnvVarsEnvVar = "RUNNER_CENSOR_ENV" ) -const successNotifyTimeout = 10 * time.Second - func usage() { _, _ = fmt.Fprintf(os.Stderr, "Usage: %s [OPTIONS] -- /path/to/program --program-args\n", filepath.Base(os.Args[0])) _, _ = fmt.Fprintf(os.Stderr, "Run the given program, only printing its output if the program exits with an error, "+ @@ -438,16 +435,8 @@ func main() { } if runOut.succeeded && *successNotifyURL != "" { - client := http.DefaultClient - client.Timeout = successNotifyTimeout - resp, err := client.Get(*successNotifyURL) - if err != nil { - deliveryErrs = append(deliveryErrs, fmt.Errorf("failed to GET success notification URL '%s': %w", *successNotifyURL, err)) - } else { - defer resp.Body.Close() - if resp.StatusCode > 200 || resp.StatusCode < 299 { - deliveryErrs = append(deliveryErrs, fmt.Errorf("failed to GET success notification URL '%s' (%s)", *successNotifyURL, resp.Status)) - } + if err := deliverSuccessNotification(*successNotifyURL); err != nil { + deliveryErrs = append(deliveryErrs, fmt.Errorf("failed to call success notification URL: %w", err)) } }