1
0
mirror of https://github.com/juanfont/headscale.git synced 2025-11-10 01:20:58 +01:00
juanfont.headscale/hscontrol/debug_test.go
Kristoffer Dalby 733fc40c3d
debug: add /debug/http-routes endpoint
Add new debug endpoint to list all registered HTTP routes with their
methods and optional names. This helps with debugging and understanding
the API surface area.

The endpoint supports both text and JSON formats:

Text format (default):
```
=== Registered HTTP Routes ===

/api/v1/                                          [ALL]
/apple                                            [GET]
/health                                           [GET]
/register/{registration_id}                       [GET]
/ts2021                                           [POST, GET]

Total routes: 14
```

JSON format:
```json
{
  "routes": [
    {
      "path": "/health",
      "methods": ["GET"]
    },
    {
      "path": "/ts2021",
      "methods": ["POST", "GET"]
    }
  ],
  "total_count": 14
}
```

Usage:
- Text: curl http://localhost:9090/debug/http-routes
- JSON: curl -H "Accept: application/json" http://localhost:9090/debug/http-routes

Changes:
- Modified debugHTTPServer() to accept router parameter
- Added collectRoutes() to walk router and collect route information
- Added debugHTTPRoutes() for text output
- Added debugHTTPRoutesJSON() for structured output
- Added HTTPRouteInfo and DebugHTTPRoutesInfo types
- Added unit tests for route listing functionality
2025-10-27 11:34:13 +01:00

63 lines
1.5 KiB
Go

package hscontrol
import (
"net/http"
"strings"
"testing"
"github.com/gorilla/mux"
)
func TestDebugHTTPRoutes(t *testing.T) {
// Create a test router with some sample routes
router := mux.NewRouter()
router.HandleFunc("/test1", testHandler1).Methods(http.MethodGet).Name("test1-route")
router.HandleFunc("/test2", testHandler2).Methods(http.MethodPost, http.MethodPut)
router.HandleFunc("/test3/{id}", testHandler3)
// Create a test Headscale instance
h := &Headscale{}
// Test text format
textOutput := h.debugHTTPRoutes(router)
if !strings.Contains(textOutput, "/test1") {
t.Errorf("Expected output to contain /test1, got: %s", textOutput)
}
if !strings.Contains(textOutput, "Total routes:") {
t.Errorf("Expected output to contain total routes count, got: %s", textOutput)
}
// Test JSON format
jsonOutput := h.debugHTTPRoutesJSON(router)
if jsonOutput.TotalCount != 3 {
t.Errorf("Expected 3 routes, got: %d", jsonOutput.TotalCount)
}
// Verify first route has the name we set
foundNamedRoute := false
for _, route := range jsonOutput.Routes {
if route.Name == "test1-route" {
foundNamedRoute = true
break
}
}
if !foundNamedRoute {
t.Error("Expected to find route with name 'test1-route'")
}
}
func testHandler1(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
func testHandler2(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
func testHandler3(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}