hw/main.go

65 lines
1.5 KiB
Go
Raw Normal View History

2018-01-09 16:26:12 -08:00
package main
import (
"encoding/json"
2018-02-01 17:36:00 -08:00
"fmt"
2018-01-09 16:26:12 -08:00
"log"
2018-03-08 13:45:07 -08:00
"math/rand"
2018-01-09 16:26:12 -08:00
"net/http"
2018-01-10 09:49:42 -08:00
"os"
2018-03-08 13:45:07 -08:00
"github.com/prometheus/client_golang/prometheus/promhttp"
"mcquay.me/metrics"
2018-01-09 16:26:12 -08:00
)
2018-03-08 13:45:07 -08:00
const version = "v0.1.0"
2018-02-01 17:36:00 -08:00
2018-01-09 16:26:12 -08:00
type v struct {
2018-01-10 09:49:42 -08:00
Hostname string `json:"hostname"`
V string `json:"version"`
2018-01-09 16:26:12 -08:00
}
func main() {
2018-03-08 13:45:07 -08:00
m, err := metrics.New("hw")
if err != nil {
log.Fatalf("metrics: %v", err)
}
2018-01-10 09:49:42 -08:00
hn, err := os.Hostname()
if err != nil {
log.Fatalf("hostname: %+v", err)
}
2018-03-08 13:45:07 -08:00
http.HandleFunc("/", m.WrapFunc("/", func(w http.ResponseWriter, req *http.Request) {
2018-01-09 16:26:12 -08:00
w.Header().Set("Content-Type", "application/json")
2018-01-10 09:49:42 -08:00
r := v{
Hostname: hn,
2018-02-01 17:36:00 -08:00
V: version,
2018-01-10 09:49:42 -08:00
}
2018-01-09 16:26:12 -08:00
if err := json.NewEncoder(w).Encode(r); err != nil {
log.Printf("json: %+v", err)
}
2018-03-08 13:45:07 -08:00
}))
http.HandleFunc("/env", m.WrapFunc("/env", func(w http.ResponseWriter, req *http.Request) {
2018-02-01 17:36:00 -08:00
for _, line := range os.Environ() {
fmt.Fprintf(w, "%v\n", line)
}
2018-03-08 13:45:07 -08:00
}))
codes := []int{
http.StatusBadGateway,
http.StatusBadRequest,
http.StatusUnauthorized,
}
http.HandleFunc("/bad", m.WrapFunc("/bad", func(w http.ResponseWriter, req *http.Request) {
code := codes[rand.Intn(len(codes))]
w.WriteHeader(code)
}))
http.HandleFunc("/live", m.WrapFunc("/live", ok))
http.HandleFunc("/ready", m.WrapFunc("/ready", ok))
http.Handle("/metrics", promhttp.Handler())
2018-01-09 16:26:12 -08:00
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatalf("listen and serve: %v", err)
}
}
2018-02-07 15:29:28 -08:00
func ok(w http.ResponseWriter, req *http.Request) {}