Skip to content

Commit

Permalink
feat(golang): include user defined routes from *_routes.go files
Browse files Browse the repository at this point in the history
In order to include custom routes:
- create a file <name>_routes.go
- define a function "register<Name>Routes" that accepts 2 arguments (router and database)

Part of #27
  • Loading branch information
php-coder committed Apr 18, 2024
1 parent 5185d21 commit 9eaeb80
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 1 deletion.
1 change: 1 addition & 0 deletions examples/go/chi/mysql/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ func main() {

r := chi.NewRouter()
registerRoutes(r, db)
registerCustomRoutes(r, db)

port := os.Getenv("PORT")
if port == "" {
Expand Down
21 changes: 21 additions & 0 deletions examples/go/chi/mysql/custom_routes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package main

import (
"encoding/json"
"net/http"

"github.com/go-chi/chi"
"github.com/jmoiron/sqlx"
)

func registerCustomRoutes(r chi.Router, db *sqlx.DB) {

r.Get("/custom/route", func(w http.ResponseWriter, r *http.Request) {
result := map[string]bool{
"custom": true,
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(&result)
})

}
3 changes: 2 additions & 1 deletion src/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,8 @@ const createApp = async (destDir, { lang }) => {
`${__dirname}/templates/${fileName}.ejs`,
{
// @todo #27 Document usage of user defined routes
'customRouteFilenames': customRouters
'customRouteFilenames': customRouters,
'capitalize': capitalize,
}
)

Expand Down
12 changes: 12 additions & 0 deletions src/templates/app.go.ejs
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
<%
// "custom_routes.go" => "registerCustomRoutes"
function fileName2registerRouterFunc(filename) {
const routerName = filename.replace(/_routes\.go$/, '')
return `register${capitalize(routerName)}Routes`
}
-%>
package main

import "fmt"
Expand Down Expand Up @@ -40,6 +47,11 @@ func main() {

r := chi.NewRouter()
registerRoutes(r, db)
<% customRouteFilenames.forEach(filename => {
const registerRouterFunc = fileName2registerRouterFunc(filename)
-%>
<%- registerRouterFunc %>(r, db)
<% }) -%>

port := os.Getenv("PORT")
if port == "" {
Expand Down

0 comments on commit 9eaeb80

Please sign in to comment.