Go
net/http and a helper that reports panics and errors.
package job
import (
"bytes"
"context"
"fmt"
"net/http"
"os"
"runtime/debug"
"time"
)
var pingURL = os.Getenv("VIVERE_PING_URL") // https://vivere.dev/p/<monitor-id>
func ping(suffix string, body []byte) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, pingURL+suffix, bytes.NewReader(body))
if resp, err := http.DefaultClient.Do(req); err == nil {
resp.Body.Close()
}
}
// Monitored runs fn and reports it, including panics.
func Monitored(fn func() error) (err error) {
ping("/start", nil)
defer func() {
if r := recover(); r != nil {
ping("/fail", []byte(fmt.Sprintf("panic: %v\n%s", r, debug.Stack())))
panic(r)
}
if err != nil {
ping("/fail", []byte(err.Error()))
} else {
ping("", nil)
}
}()
return fn()
}