diff --git a/cmd/jiralert/content.go b/cmd/jiralert/content.go new file mode 100644 index 0000000..486ea76 --- /dev/null +++ b/cmd/jiralert/content.go @@ -0,0 +1,113 @@ +package main + +import ( + "fmt" + "html/template" + "net/http" + + "github.com/free/jiralert" +) + +const ( + docsUrl = "https://github.com/free/jiralert#readme" + templates = ` + {{ define "page" -}} + + + JIRAlert + + + + + {{template "content" .}} + + + {{- end }} + + {{ define "content.home" -}} +

This is JIRAlert, a + webhook receiver for + Prometheus Alertmanager. + {{- end }} + + {{ define "content.config" -}} +

Configuration

+
{{ .Config }}
+ {{- end }} + + {{ define "content.error" -}} +

Error

+
{{ .Err }}
+ {{- end }} + ` +) + +type tdata struct { + DocsUrl string + + // `/config` only + Config string + + // `/error` only + Err error +} + +var ( + allTemplates = template.Must(template.New("").Parse(templates)) + homeTemplate = pageTemplate("home") + configTemplate = pageTemplate("config") + errorTemplate = pageTemplate("error") +) + +func pageTemplate(name string) *template.Template { + pageTemplate := fmt.Sprintf(`{{define "content"}}{{template "content.%s" .}}{{end}}{{template "page" .}}`, name) + return template.Must(template.Must(allTemplates.Clone()).Parse(pageTemplate)) +} + +// HomeHandlerFunc is the HTTP handler for the home page (`/`). +func HomeHandlerFunc() func(http.ResponseWriter, *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + homeTemplate.Execute(w, &tdata{ + DocsUrl: docsUrl, + }) + } +} + +// ConfigHandlerFunc is the HTTP handler for the `/config` page. It outputs the configuration marshaled in YAML format. +func ConfigHandlerFunc(config *jiralert.Config) func(http.ResponseWriter, *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + configTemplate.Execute(w, &tdata{ + DocsUrl: docsUrl, + Config: config.String(), + }) + } +} + +// HandleError is an error handler that other handlers defer to in case of error. It is important to not have written +// anything to w before calling HandleError(), or the 500 status code won't be set (and the content might be mixed up). +func HandleError(err error, metricsPath string, w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + errorTemplate.Execute(w, &tdata{ + DocsUrl: docsUrl, + Err: err, + }) +} diff --git a/cmd/jiralert/main.go b/cmd/jiralert/main.go index f1a34d4..fecbb57 100644 --- a/cmd/jiralert/main.go +++ b/cmd/jiralert/main.go @@ -98,6 +98,9 @@ func main() { requestTotal.WithLabelValues(conf.Name, "200").Inc() }) + http.HandleFunc("/", HomeHandlerFunc()) + http.HandleFunc("/config", ConfigHandlerFunc(config)) + http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { http.Error(w, "OK", http.StatusOK) }) http.Handle("/metrics", promhttp.Handler()) if os.Getenv("PORT") != "" {