Debug path where route was created

This commit is contained in:
Achim Rohn
2025-08-28 13:16:30 +02:00
parent 644f3dcf31
commit 46c411f9f3
+24 -1
View File
@@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"net/http"
"runtime"
"runtime/debug"
"sort"
"strings"
@@ -316,6 +317,16 @@ func addLanguageToPath(path string, language Language) string {
return "/" + string(language) + path
}
// getCallerLocation returns the file location of the function that called NewCommonHtmxRoute
func getCallerLocation() string {
// Skip 2 frames: getCallerLocation itself and NewCommonHtmxRoute
_, file, line, ok := runtime.Caller(3)
if !ok {
return "unknown location"
}
return fmt.Sprintf("%s:%d", file, line)
}
type CommonHtmxRoute struct {
Paths LanguagePaths
RouteFunc HtmxRouteFunc
@@ -323,6 +334,7 @@ type CommonHtmxRoute struct {
ActivePath *ActivePath
Method string
HtmxMethod HtmxHttpMethodFunction
createdLocation string
}
func (h CommonHtmxRoute) GetPaths() LanguagePaths {
@@ -355,12 +367,14 @@ func (h CommonHtmxRoute) RedirectToThisRoute(c HtmxContext, params LocationRedir
func NewCommonHtmxRoute(routeFunc HtmxRouteFunc, paths LanguagePaths, method string,
htmxMethod HtmxHttpMethodFunction) *CommonHtmxRoute {
route := &CommonHtmxRoute{RouteFunc: routeFunc, Paths: paths, Method: method, HtmxMethod: htmxMethod}
route := &CommonHtmxRoute{RouteFunc: routeFunc, Paths: paths, Method: method, HtmxMethod: htmxMethod,
createdLocation: getCallerLocation()}
GlobalHtmxRoutesInstance.Add(route)
return route
}
func (h CommonHtmxRoute) Execute(c HtmxContext) {
h.traceLocation()
h.RouteFunc(c)
}
@@ -369,9 +383,12 @@ func (h CommonHtmxRoute) SetActivePath(activePath *ActivePath) HtmxRoute {
return h
}
var HtmxRouteDebugTrace bool = false
func (h CommonHtmxRoute) AddWithMethod(method string, server HtmxServer) {
for language, path := range h.Paths {
server.GetHttpServer().HandleFunc(method+" "+addLanguageToPath(path, language), func(res http.ResponseWriter, req *http.Request) {
h.traceLocation()
context := NewHtmxContext(req, res, language)
context.SetPathTemplate(addLanguageToPath(path, language))
context.SetAllRoutes(server.GetAllRoutes())
@@ -383,6 +400,12 @@ func (h CommonHtmxRoute) AddWithMethod(method string, server HtmxServer) {
}
}
func (h CommonHtmxRoute) traceLocation() {
if HtmxRouteDebugTrace {
Debug(h.createdLocation)
}
}
func (h CommonHtmxRoute) Add(server HtmxServer) {
server.Add(h)
h.AddWithMethod(h.Method, server)