From 9eaeb80ccf37e02f664e856420df6db7aa0d38ce Mon Sep 17 00:00:00 2001 From: Slava Semushin Date: Thu, 18 Apr 2024 07:57:53 +0700 Subject: [PATCH] feat(golang): include user defined routes from *_routes.go files In order to include custom routes: - create a file _routes.go - define a function "registerRoutes" that accepts 2 arguments (router and database) Part of #27 --- examples/go/chi/mysql/app.go | 1 + examples/go/chi/mysql/custom_routes.go | 21 +++++++++++++++++++++ src/cli.js | 3 ++- src/templates/app.go.ejs | 12 ++++++++++++ 4 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 examples/go/chi/mysql/custom_routes.go diff --git a/examples/go/chi/mysql/app.go b/examples/go/chi/mysql/app.go index cdf9d4f..1702e59 100644 --- a/examples/go/chi/mysql/app.go +++ b/examples/go/chi/mysql/app.go @@ -40,6 +40,7 @@ func main() { r := chi.NewRouter() registerRoutes(r, db) + registerCustomRoutes(r, db) port := os.Getenv("PORT") if port == "" { diff --git a/examples/go/chi/mysql/custom_routes.go b/examples/go/chi/mysql/custom_routes.go new file mode 100644 index 0000000..9b9abc9 --- /dev/null +++ b/examples/go/chi/mysql/custom_routes.go @@ -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) + }) + +} diff --git a/src/cli.js b/src/cli.js index a702734..7439712 100755 --- a/src/cli.js +++ b/src/cli.js @@ -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, } ) diff --git a/src/templates/app.go.ejs b/src/templates/app.go.ejs index cdf9d4f..21e447f 100644 --- a/src/templates/app.go.ejs +++ b/src/templates/app.go.ejs @@ -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" @@ -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 == "" {