82 lines
1.9 KiB
Go
82 lines
1.9 KiB
Go
package main
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/labstack/echo-contrib/echoprometheus"
|
|
"github.com/labstack/echo/v4"
|
|
"github.com/labstack/echo/v4/middleware"
|
|
"github.com/labstack/gommon/log"
|
|
"github.com/prometheus/client_golang/prometheus"
|
|
)
|
|
|
|
const TimeFormat = "2006-01-02 15:04:05"
|
|
|
|
func main() {
|
|
app := echo.New()
|
|
app.Logger.SetLevel(log.INFO)
|
|
|
|
app.Use(middleware.RecoverWithConfig(middleware.RecoverConfig{
|
|
StackSize: 1 << 10,
|
|
LogLevel: log.ERROR,
|
|
}))
|
|
app.Use(middleware.Secure())
|
|
|
|
app.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
|
|
Format: "${time_custom} ${method} ${uri} ---> ${status} in ${latency_human} (${bytes_out} bytes)\n",
|
|
CustomTimeFormat: TimeFormat,
|
|
}))
|
|
app.Use(middleware.RemoveTrailingSlash())
|
|
|
|
app.OnAddRouteHandler = func(host string, route echo.Route, handler echo.HandlerFunc, middleware []echo.MiddlewareFunc) {
|
|
now := time.Now()
|
|
fmt.Printf("%s registered %-6s %s\n", now.Format(TimeFormat), route.Method, route.Path)
|
|
}
|
|
app.HTTPErrorHandler = func(err error, c echo.Context) {
|
|
if c.Response().Committed {
|
|
log.Error(err)
|
|
return
|
|
}
|
|
|
|
code := http.StatusInternalServerError
|
|
var response any = err.Error()
|
|
|
|
var httpErr *echo.HTTPError
|
|
if errors.As(err, &httpErr) {
|
|
code = httpErr.Code
|
|
response = httpErr
|
|
}
|
|
|
|
if code >= 500 {
|
|
log.Error(err)
|
|
}
|
|
|
|
err2 := c.JSON(code, response)
|
|
if err2 != nil {
|
|
log.Error(err2)
|
|
}
|
|
}
|
|
|
|
registry := prometheus.NewRegistry()
|
|
counter := prometheus.NewCounter(
|
|
prometheus.CounterOpts{
|
|
Name: "custom_requests_total",
|
|
Help: "How many HTTP requests processed, partitioned by status code and HTTP method.",
|
|
},
|
|
)
|
|
if err := registry.Register(counter); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
app.GET("/", func(c echo.Context) error {
|
|
return c.JSON(http.StatusOK, "Hello, World!")
|
|
})
|
|
|
|
app.GET("/metrics", echoprometheus.NewHandlerWithConfig(echoprometheus.HandlerConfig{Gatherer: registry}))
|
|
|
|
log.Fatal(app.Start(":1323"))
|
|
}
|