Skip to content

Commit

Permalink
improve gin support
Browse files Browse the repository at this point in the history
Use gin.IRouter interface instead of *gin.Engine
Switch custom middleware code to gin middleware

Original changes: deepmap#530
  • Loading branch information
mrmelphin committed Apr 6, 2022
1 parent 71a6fca commit 56a2a94
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 12 deletions.
15 changes: 10 additions & 5 deletions pkg/codegen/templates/gin/gin-register.tmpl
@@ -1,23 +1,28 @@
// GinServerOptions provides options for the Gin server.
type GinServerOptions struct {
BaseURL string
Middlewares []MiddlewareFunc
Middlewares []gin.HandlerFunc
}

// keeping for backward compatibility
type MiddlewareFunc = gin.HandlerFunc

// RegisterHandlers creates http.Handler with routing matching OpenAPI spec.
func RegisterHandlers(router *gin.Engine, si ServerInterface) *gin.Engine {
func RegisterHandlers(router gin.IRouter, si ServerInterface) gin.IRouter {
return RegisterHandlersWithOptions(router, si, GinServerOptions{})
}

// RegisterHandlersWithOptions creates http.Handler with additional options
func RegisterHandlersWithOptions(router *gin.Engine, si ServerInterface, options GinServerOptions) *gin.Engine {
func RegisterHandlersWithOptions(router gin.IRouter, si ServerInterface, options GinServerOptions) gin.IRouter {
{{if .}}wrapper := ServerInterfaceWrapper{
Handler: si,
HandlerMiddlewares: options.Middlewares,
}
{{end}}

router = router.Group(options.BaseURL, options.Middlewares...)

{{range .}}
router.{{.Method }}(options.BaseURL+"{{.Path | swaggerUriToGinUri }}", wrapper.{{.OperationId}})
router.{{.Method }}("{{.Path | swaggerUriToGinUri }}", wrapper.{{.OperationId}})
{{end}}
return router
}
7 changes: 0 additions & 7 deletions pkg/codegen/templates/gin/gin-wrappers.tmpl
@@ -1,11 +1,8 @@
// ServerInterfaceWrapper converts contexts to parameters.
type ServerInterfaceWrapper struct {
Handler ServerInterface
HandlerMiddlewares []MiddlewareFunc
}

type MiddlewareFunc func(c *gin.Context)

{{range .}}{{$opid := .OperationId}}

// {{$opid}} operation middleware
Expand Down Expand Up @@ -165,10 +162,6 @@ func (siw *ServerInterfaceWrapper) {{$opid}}(c *gin.Context) {
{{end}}
{{end}}

for _, middleware := range siw.HandlerMiddlewares {
middleware(c)
}

siw.Handler.{{.OperationId}}(c{{genParamNames .PathParams}}{{if .RequiresParamObject}}, params{{end}})
}
{{end}}

0 comments on commit 56a2a94

Please sign in to comment.