Skip to content

Commit

Permalink
Use router group for /user path.
Browse files Browse the repository at this point in the history
Avoids repetition and makes things cleaner.

Signed-off-by: Ville Valkonen <weezel@users.noreply.github.com>
  • Loading branch information
weezel committed Jun 1, 2024
1 parent 546d003 commit 1d2a850
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 8 deletions.
14 changes: 9 additions & 5 deletions cmd/webserver/routes/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,15 @@ import (

// Add routes to our web server
func AddRoutes(httpServer *httpserver.HTTPServer, queries *sqlc.Queries) {
ctrl := user.NewHandlerController(queries) // TODO
userRouterGroup := httpServer.NewRouterGroup("/user")
ctrl := user.NewHandlerController(
userRouterGroup,
queries,
)

// User related functionality
httpServer.GET("/user/", ctrl.IndexHandler)
httpServer.GET("/user/:name", ctrl.GetHandler)
httpServer.POST("/user", ctrl.PostHandler)
httpServer.DELETE("/user", ctrl.DeleteHandler)
userRouterGroup.GET("/", ctrl.IndexHandler)
userRouterGroup.GET(":name", ctrl.GetHandler)
userRouterGroup.POST("", ctrl.PostHandler)
userRouterGroup.DELETE("", ctrl.DeleteHandler)
}
12 changes: 9 additions & 3 deletions cmd/webserver/routes/user/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,20 @@ import (
"context"

"weezel/example-gin/pkg/generated/sqlc"

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

type HandlerController struct {
querier sqlc.Querier
querier sqlc.Querier
userRouterGroup *gin.RouterGroup
}

func NewHandlerController(db sqlc.Querier) *HandlerController {
return &HandlerController{querier: db}
func NewHandlerController(userRouterGroup *gin.RouterGroup, db sqlc.Querier) *HandlerController {
return &HandlerController{
userRouterGroup: userRouterGroup,
querier: db,
}
}

// MockHandlerController introduces method calls that can be implemented on test case basis
Expand Down
5 changes: 5 additions & 0 deletions pkg/httpserver/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ func WithCustomHealthCheckHandler(healthCheckHandler gin.HandlerFunc) Option {

// Initializing the server in a goroutine so that it won't block
func (h *HTTPServer) Start() {
l.Logger.Info().Msgf("Starting web server on %s", h.httpServer.Addr)
go func() {
if err := h.httpServer.ListenAndServe(); err != nil &&
errors.Is(err, http.ErrServerClosed) {
Expand All @@ -157,6 +158,10 @@ func (h *HTTPServer) Shutdown(ctx context.Context) {
}
}

func (h *HTTPServer) NewRouterGroup(path string, handlers ...gin.HandlerFunc) *gin.RouterGroup {
return h.ginEngine.Group(path, handlers...)
}

func (h *HTTPServer) Handle(httpMethod, relativePath string, handlers ...gin.HandlerFunc) {
h.ginEngine.Handle(httpMethod, relativePath, handlers...)
}
Expand Down

0 comments on commit 1d2a850

Please sign in to comment.