|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "log" |
| 5 | + "net/http" |
| 6 | + "os" |
| 7 | + "os/signal" |
| 8 | + "syscall" |
| 9 | + |
| 10 | + "github.com/kataras/iris/v12" |
| 11 | + "github.com/prometheus/client_golang/prometheus/promhttp" |
| 12 | + metrics "github.com/slok/go-http-metrics/metrics/prometheus" |
| 13 | + "github.com/slok/go-http-metrics/middleware" |
| 14 | + irismiddleware "github.com/slok/go-http-metrics/middleware/iris" |
| 15 | +) |
| 16 | + |
| 17 | +const ( |
| 18 | + srvAddr = ":8080" |
| 19 | + metricsAddr = ":8081" |
| 20 | +) |
| 21 | + |
| 22 | +func main() { |
| 23 | + // Create our middleware. |
| 24 | + mdlw := middleware.New(middleware.Config{ |
| 25 | + Recorder: metrics.NewRecorder(metrics.Config{}), |
| 26 | + }) |
| 27 | + |
| 28 | + // Create Iris engine and global middleware. |
| 29 | + app := iris.New() |
| 30 | + app.Use(irismiddleware.Handler("", mdlw)) |
| 31 | + |
| 32 | + // Add our handler. |
| 33 | + app.Get("/", func(ctx iris.Context) { |
| 34 | + ctx.StatusCode(iris.StatusAccepted) |
| 35 | + _, _ = ctx.WriteString("Hello world!") |
| 36 | + }) |
| 37 | + |
| 38 | + app.Get("/json", func(ctx iris.Context) { |
| 39 | + ctx.JSON(map[string]string{"hello": "world"}) // nolint: errcheck |
| 40 | + }) |
| 41 | + |
| 42 | + app.Get("/wrong", func(ctx iris.Context) { |
| 43 | + ctx.StatusCode(iris.StatusTooManyRequests) |
| 44 | + _, _ = ctx.WriteString("oops") |
| 45 | + |
| 46 | + }) |
| 47 | + |
| 48 | + err := app.Build() |
| 49 | + if err != nil { |
| 50 | + panic(err) |
| 51 | + } |
| 52 | + |
| 53 | + // Serve our handler. |
| 54 | + go func() { |
| 55 | + log.Printf("server listening at %s", srvAddr) |
| 56 | + if err := http.ListenAndServe(srvAddr, app); err != nil { |
| 57 | + log.Panicf("error while serving: %s", err) |
| 58 | + } |
| 59 | + }() |
| 60 | + |
| 61 | + // Serve our metrics. |
| 62 | + go func() { |
| 63 | + log.Printf("metrics listening at %s", metricsAddr) |
| 64 | + if err := http.ListenAndServe(metricsAddr, promhttp.Handler()); err != nil { |
| 65 | + log.Panicf("error while serving metrics: %s", err) |
| 66 | + } |
| 67 | + }() |
| 68 | + |
| 69 | + // Wait until some signal is captured. |
| 70 | + sigC := make(chan os.Signal, 1) |
| 71 | + signal.Notify(sigC, syscall.SIGTERM, syscall.SIGINT) |
| 72 | + <-sigC |
| 73 | +} |
0 commit comments