Skip to content

Commit 9eaeb80

Browse files
committed
feat(golang): include user defined routes from *_routes.go files
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
1 parent 5185d21 commit 9eaeb80

File tree

4 files changed

+36
-1
lines changed

4 files changed

+36
-1
lines changed

examples/go/chi/mysql/app.go

+1
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ func main() {
4040

4141
r := chi.NewRouter()
4242
registerRoutes(r, db)
43+
registerCustomRoutes(r, db)
4344

4445
port := os.Getenv("PORT")
4546
if port == "" {
+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package main
2+
3+
import (
4+
"encoding/json"
5+
"net/http"
6+
7+
"github.com/go-chi/chi"
8+
"github.com/jmoiron/sqlx"
9+
)
10+
11+
func registerCustomRoutes(r chi.Router, db *sqlx.DB) {
12+
13+
r.Get("/custom/route", func(w http.ResponseWriter, r *http.Request) {
14+
result := map[string]bool{
15+
"custom": true,
16+
}
17+
w.Header().Set("Content-Type", "application/json")
18+
json.NewEncoder(w).Encode(&result)
19+
})
20+
21+
}

src/cli.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,8 @@ const createApp = async (destDir, { lang }) => {
104104
`${__dirname}/templates/${fileName}.ejs`,
105105
{
106106
// @todo #27 Document usage of user defined routes
107-
'customRouteFilenames': customRouters
107+
'customRouteFilenames': customRouters,
108+
'capitalize': capitalize,
108109
}
109110
)
110111

src/templates/app.go.ejs

+12
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,10 @@
1+
<%
2+
// "custom_routes.go" => "registerCustomRoutes"
3+
function fileName2registerRouterFunc(filename) {
4+
const routerName = filename.replace(/_routes\.go$/, '')
5+
return `register${capitalize(routerName)}Routes`
6+
}
7+
-%>
18
package main
29

310
import "fmt"
@@ -40,6 +47,11 @@ func main() {
4047

4148
r := chi.NewRouter()
4249
registerRoutes(r, db)
50+
<% customRouteFilenames.forEach(filename => {
51+
const registerRouterFunc = fileName2registerRouterFunc(filename)
52+
-%>
53+
<%- registerRouterFunc %>(r, db)
54+
<% }) -%>
4355

4456
port := os.Getenv("PORT")
4557
if port == "" {

0 commit comments

Comments
 (0)