This commit is contained in:
2023-07-24 18:22:36 +02:00
parent a259bb6dbc
commit 8ae9a0f107
3 changed files with 113 additions and 14 deletions

View File

@@ -1,8 +1,12 @@
package ginext
import (
"fmt"
"github.com/gin-gonic/gin"
"gogs.mikescher.com/BlackForestBytes/goext/langext"
"gogs.mikescher.com/BlackForestBytes/goext/mathext"
"net/http"
"strings"
"time"
)
@@ -13,6 +17,15 @@ type GinWrapper struct {
allowCors bool
ginDebug bool
requestTimeout time.Duration
routeSpecs []ginRouteSpec
}
type ginRouteSpec struct {
Method string
URL string
Middlewares []string
Handler string
}
func NewEngine(allowCors bool, ginDebug bool, timeout time.Duration) *GinWrapper {
@@ -33,18 +46,63 @@ func NewEngine(allowCors bool, ginDebug bool, timeout time.Duration) *GinWrapper
engine.Use(CorsMiddleware())
}
// do not debug-print routes
gin.DebugPrintRouteFunc = func(_, _, _ string, _ int) {}
if ginDebug {
gin.SetMode(gin.ReleaseMode)
ginlogger := gin.Logger()
engine.Use(func(context *gin.Context) {
if !wrapper.SuppressGinLogs {
ginlogger(context)
}
})
} else {
gin.SetMode(gin.DebugMode)
}
return wrapper
}
func (w *GinWrapper) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
if w.ginDebug {
w.debugPrintRoutes()
}
w.engine.ServeHTTP(writer, request)
}
func (w *GinWrapper) debugPrintRoutes() {
lines := make([][4]string, 0)
pad := [4]int{0, 0, 0, 0}
for _, spec := range w.routeSpecs {
line := [4]string{
spec.Method,
spec.URL,
strings.Join(spec.Middlewares, " --> "),
spec.Method,
}
lines = append(lines, line)
pad[0] = mathext.Max(pad[0], len(line[0]))
pad[1] = mathext.Max(pad[1], len(line[1]))
pad[2] = mathext.Max(pad[2], len(line[2]))
pad[3] = mathext.Max(pad[3], len(line[3]))
}
for _, line := range lines {
fmt.Printf("Gin-Route: [%s] @ %s --> %s --> %s",
langext.StrPadRight(line[0], " ", pad[0]),
langext.StrPadRight(line[1], " ", pad[1]),
langext.StrPadRight(line[2], " ", pad[2]),
langext.StrPadRight(line[3], " ", pad[3]))
}
}