feat: add BeforePrepare for operation of swagger API (#14048)

Signed-off-by: He Weiwei <hweiwei@vmware.com>
This commit is contained in:
He Weiwei 2021-01-22 10:44:25 +08:00 committed by GitHub
parent 19a72cf350
commit 50b40445f4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 17 additions and 1 deletions

View File

@ -15,9 +15,11 @@
package handler
import (
"context"
"log"
"net/http"
rmiddleware "github.com/go-openapi/runtime/middleware"
lib_http "github.com/goharbor/harbor/src/lib/http"
"github.com/goharbor/harbor/src/server/middleware"
"github.com/goharbor/harbor/src/server/middleware/blob"
@ -52,11 +54,17 @@ func New() http.Handler {
api.RegisterMiddleware("DeleteArtifact", quota.RefreshForProjectMiddleware())
api.RegisterMiddleware("DeleteRepository", quota.RefreshForProjectMiddleware())
api.BeforePrepare = beforePrepare
api.ServeError = serveError
return h
}
// function is called before the Prepare of the operation
func beforePrepare(ctx context.Context, operation string, params interface{}) rmiddleware.Responder {
return nil
}
// Before executing operation handler, go-swagger will bind a parameters object to a request and validate the request,
// it will return directly when bind and validate failed.
// The response format of the default ServeError implementation does not match the internal error response format.

View File

@ -90,6 +90,9 @@ type {{ pascalize .Name }}API struct {
// operationMiddlewares middleware for operations
operationMiddlewares map[string]middleware.Builder
// BeforePrepare is called before the Prepare of the operation
BeforePrepare func(context.Context, string, interface{}) middleware.Responder
// BasicAuthenticator generates a runtime.Authenticator from the supplied basic auth function.
// It has a default implementation in the security package, however you can replace it for your particular usage.
BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator
@ -375,4 +378,4 @@ func ({{.ReceiverName}} *{{ pascalize .Name }}API) RegisterProducer(mediaType st
// RegisterMiddleware allows you to add (or override) a middleware for operation.
func ({{.ReceiverName}} *{{ pascalize .Name }}API) RegisterMiddleware(operation string, builder middleware.Builder) {
{{.ReceiverName}}.operationMiddlewares[operation] = builder
}
}

View File

@ -151,6 +151,11 @@ func HandlerAPI(c Config) (http.Handler, *{{.Package}}.{{ pascalize .Name }}API,
{{ if .Authorized -}}
ctx = storeAuth(ctx, principal)
{{ end -}}
if api.BeforePrepare != nil {
if res := api.BeforePrepare(ctx, "{{pascalize .Name}}", &params); res != nil {
return res
}
}
if res := c.{{pascalize .Package}}API.Prepare(ctx, "{{pascalize .Name}}", &params); res != nil {
return res
}