Ping CronMissed from Go

On this page

Go's net/http is all a ping needs. This helper builds a client with a timeout, drains and closes every response so connections are reused, and wraps your job in the start, success and failure signals.

What should a Go job send?

  • A request to /start before the work, so CronMissed can time the run and notice a job that never finishes.
  • A request to the plain URL when the work succeeded, or to /fail when it did not. /<exit status> works too: 0 is a success and any other number is a failure.
  • The end of the output in the request body, up to 100,000 bytes, so the alert shows the error without a trip to the server.

What is the helper?

monitor.go
package monitor

import (
	"context"
	"io"
	"net/http"
	"strings"
	"time"
)

var client = &http.Client{Timeout: 10 * time.Second}

// Ping sends one signal. suffix is "", "/start", "/fail" or "/<exit status>".
func Ping(ctx context.Context, base, suffix, body string) {
	method := http.MethodGet
	if body != "" {
		method = http.MethodPost
	}
	req, err := http.NewRequestWithContext(ctx, method, base+suffix, strings.NewReader(body))
	if err != nil {
		return
	}
	resp, err := client.Do(req)
	if err != nil {
		return // a lost ping must never break the job
	}
	defer resp.Body.Close()
	_, _ = io.Copy(io.Discard, resp.Body)
}

// Run reports a job's start, then its success, or its failure with the end of the error text.
func Run(ctx context.Context, base string, job func(context.Context) error) error {
	Ping(ctx, base, "/start", "")
	if err := job(ctx); err != nil {
		text := err.Error()
		if len(text) > 100000 {
			text = text[len(text)-100000:]
		}
		Ping(ctx, base, "/fail", text)
		return err
	}
	Ping(ctx, base, "", "")
	return nil
}

Keep the ping URL in an environment variable or a secret store, never in a public repository: the URL is the check's only credential.

Questions and answers

Why drain the response body?
An unread body keeps the connection from being reused. For a job that pings twice, it makes little difference, but the habit stops leaks in long-running programs.
What about a program that panics?
Recover in the caller, send /fail with the panic text, then re-panic or exit non-zero. A program killed outright sends nothing, which the check reports as a missed run.
Create the check these snippets report to

Make a check, copy its ping URL into the snippet, and run the job once.

Start monitoring