Skip to content

Commit

Permalink
Merge pull request #21 from kepkin/feature/custom-routing
Browse files Browse the repository at this point in the history
Add custom router to register middleware.
  • Loading branch information
kepkin authored May 13, 2020
2 parents a19dba7 + eb5ee48 commit dc62207
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
14 changes: 14 additions & 0 deletions internal/generator/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,20 @@ func RegisterRoutes(r *gin.Engine, api {{ .InterfaceName }}) {
{{- end }}
{{- end }}
{{ end -}}
}
type HandlerRegister func(operationID, httpMethod, relativePath string, handler gin.HandlerFunc)
// CustomRouter
func RegisterRoutesCustom(handlerRegister HandlerRegister, api {{ .InterfaceName }}) {
e := &{{ .InterfaceName }}Server{api}
{{ range $url, $m := .Paths -}}
{{- range $methodName, $method := (dict "GET" $m.Get "POST" $m.Post "PATCH" $m.Patch "DELETE" $m.Delete "PUT" $m.Put "OPTIONS" $m.Options) }}
{{- with $method }}
handlerRegister("{{ .OperationID }}", "{{ $methodName }}", "{{ ConvertUrl $url }}", e._{{ $.InterfaceName }}_{{ .OperationID }}_Handler)
{{- end }}
{{- end }}
{{ end -}}
}`))

func (Generator) makeRouter(wr io.Writer, sp openapi3.Spec) error {
Expand Down
18 changes: 18 additions & 0 deletions test/api/api_gorest.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 26 additions & 0 deletions test/generated_api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,3 +116,29 @@ func TestCreateUser(t *testing.T) {

assert.Equal(t, response.Body.Bytes(), photoBytes)
}


func TestCustomRouteWithMiddleWare(t *testing.T) {
r := gin.New()
api.RegisterRoutesCustom(func(operationID, httpMethod, relativePath string, handler gin.HandlerFunc) {
handlers := make([]gin.HandlerFunc, 0)

if operationID == "GetUser" {
handlers = append(handlers, func(c *gin.Context){
c.AbortWithStatus(401)
})
}

handlers = append(handlers, handler)
r.Handle(httpMethod, relativePath, handlers...)
}, api.NewPaymentGatewayAPI())

// Go to route with middle ware
request := httptest.NewRequest(http.MethodGet, "/v1/user/123", nil)
response := httptest.NewRecorder()

r.ServeHTTP(response, request)
if !assert.Equal(t, http.StatusUnauthorized, response.Code, response.Body.String()) {
return
}
}

0 comments on commit dc62207

Please sign in to comment.