Skip to content

Commit

Permalink
added a way to list routes
Browse files Browse the repository at this point in the history
  • Loading branch information
cmarcoin authored and Josquin Cornec committed May 31, 2024
1 parent 887dbc1 commit a18c4e1
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 4 deletions.
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,14 @@ postgres = "host=localhost port=5432 user=postgres password=toto dbname=postgres
[stats]
db_url = "postgres://postgres:toto@localhost:5432/datapilogs"
```

- Exécuter le binaire


Il est possible de lister les routes en exécutant la commande suivante (Il faut avoir buildé le binaire avec `go build`):
```bash
./datapi --list-routes=true
```

## Conteneur
- `cd build-container`
- `./build.sh`
Expand Down
16 changes: 13 additions & 3 deletions pkg/core/datapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
package core

import (
"flag"
"fmt"
"log"
"log/slog"
Expand Down Expand Up @@ -121,9 +122,18 @@ func AddEndpoint(router *gin.Engine, path string, endpoint Endpoint, handlers ..
func StartAPI(router *gin.Engine) {
addr := viper.GetString("bind")
log.Print("Running API on " + addr)
err := router.Run(addr)
if err != nil {
fmt.Println(err.Error())

listOnly := flag.Bool("list-routes", false, "List all registered routes and exit")
flag.Parse()

if *listOnly {
utils.ListRoutes(router)
} else {
err := router.Run(addr)

if err != nil {
fmt.Println(err.Error())
}
}
}

Expand Down
37 changes: 37 additions & 0 deletions pkg/utils/routes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package utils

import (
"fmt"
"sort"
"strings"

"github.com/gin-gonic/gin"
)

// ListRoutes prints all registered routes in the Gin application, grouped by the first segment of the route
func ListRoutes(router *gin.Engine) {
routeMap := make(map[string][]string)

for _, route := range router.Routes() {
segments := strings.Split(route.Path, "/")
if len(segments) > 1 {
firstSegment := segments[1]
key := "/" + firstSegment
routeMap[key] = append(routeMap[key], fmt.Sprintf("%s -> %s", route.Path, route.Handler))
}
}

firstSegments := make([]string, 0, len(routeMap))
for k := range routeMap {
firstSegments = append(firstSegments, k)
}
sort.Strings(firstSegments)

for _, fs := range firstSegments {
fmt.Printf("%s:\n", fs)
for _, route := range routeMap[fs] {
fmt.Println(" " + route)
}
fmt.Println()
}
}

0 comments on commit a18c4e1

Please sign in to comment.