|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "log" |
| 5 | + "net/http" |
| 6 | + "os" |
| 7 | + "os/signal" |
| 8 | + "syscall" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/justinas/alice" |
| 12 | + "github.com/prometheus/client_golang/prometheus/promhttp" |
| 13 | + metrics "github.com/slok/go-http-metrics/metrics/prometheus" |
| 14 | + "github.com/slok/go-http-metrics/middleware" |
| 15 | + "github.com/slok/go-http-metrics/middleware/std" |
| 16 | +) |
| 17 | + |
| 18 | +const ( |
| 19 | + srvAddr = ":8080" |
| 20 | + metricsAddr = ":8081" |
| 21 | +) |
| 22 | + |
| 23 | +func main() { |
| 24 | + // Create our middleware. |
| 25 | + mdlw := middleware.New(middleware.Config{ |
| 26 | + Recorder: metrics.NewRecorder(metrics.Config{}), |
| 27 | + }) |
| 28 | + |
| 29 | + // Create our server. |
| 30 | + mux := http.NewServeMux() |
| 31 | + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { |
| 32 | + time.Sleep(200 * time.Millisecond) |
| 33 | + w.WriteHeader(http.StatusOK) |
| 34 | + }) |
| 35 | + mux.HandleFunc("/test1", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusCreated) }) |
| 36 | + mux.HandleFunc("/test1/test2", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusAccepted) }) |
| 37 | + mux.HandleFunc("/test1/test4", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNonAuthoritativeInfo) }) |
| 38 | + mux.HandleFunc("/test2", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) }) |
| 39 | + mux.HandleFunc("/test3", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusResetContent) }) |
| 40 | + |
| 41 | + // Wrap with middleware. |
| 42 | + h := alice.New(std.HandlerProvider("", mdlw)).Then(mux) |
| 43 | + |
| 44 | + // Serve our handler. |
| 45 | + go func() { |
| 46 | + log.Printf("server listening at %s", srvAddr) |
| 47 | + if err := http.ListenAndServe(srvAddr, h); err != nil { |
| 48 | + log.Panicf("error while serving: %s", err) |
| 49 | + } |
| 50 | + }() |
| 51 | + |
| 52 | + // Serve our metrics. |
| 53 | + go func() { |
| 54 | + log.Printf("metrics listening at %s", metricsAddr) |
| 55 | + if err := http.ListenAndServe(metricsAddr, promhttp.Handler()); err != nil { |
| 56 | + log.Panicf("error while serving metrics: %s", err) |
| 57 | + } |
| 58 | + }() |
| 59 | + |
| 60 | + // Wait until some signal is captured. |
| 61 | + sigC := make(chan os.Signal, 1) |
| 62 | + signal.Notify(sigC, syscall.SIGTERM, syscall.SIGINT) |
| 63 | + <-sigC |
| 64 | +} |
0 commit comments