github.com/thetreep/go-swagger@v0.0.0-20240223100711-35af64f14f01/generator/templates/contrib/stratoscale/server/configureapi.gotmpl (about)

     1  // Code generated by go-swagger; DO NOT EDIT.
     2  
     3  
     4  {{ if .Copyright -}}// {{ comment .Copyright -}}{{ end }}
     5  
     6  
     7  package {{ .APIPackage }}
     8  
     9  import (
    10  	"context"
    11  	"crypto/tls"
    12  	"net/http"
    13  	"log"
    14  	"fmt"
    15  
    16  	"github.com/go-openapi/errors"
    17  	"github.com/go-openapi/loads"
    18  	"github.com/go-openapi/runtime"
    19  	"github.com/go-openapi/runtime/middleware"
    20  	"github.com/go-openapi/runtime/security"
    21  
    22    {{ imports .DefaultImports }}
    23    {{ imports .Imports }}
    24  )
    25  {{ $package := .Package }}
    26  
    27  type contextKey string
    28  
    29  const AuthKey contextKey = "Auth"
    30  
    31  {{ range .OperationGroups -}}
    32  //go:generate mockery --name {{ pascalize .Name}}API --inpackage
    33  
    34  /* {{ pascalize .Name }}API {{ .Description }} */
    35  type {{ pascalize .Name }}API interface {
    36  {{ range .Operations -}}
    37  	{{ if .Summary -}}
    38  	/* {{ pascalize .Name }} {{ .Summary }} */
    39  	{{ else if .Description -}}
    40  	/* {{ pascalize .Name }} {{ .Description }} */
    41  	{{ end -}}
    42  	{{ pascalize .Name }}(ctx context.Context, params {{.Package}}.{{ pascalize .Name }}Params) middleware.Responder
    43  
    44  {{ end -}}
    45  }
    46  {{ end }}
    47  
    48  // Config is configuration for Handler
    49  type Config struct {
    50  	{{ range .OperationGroups -}}
    51  	{{ pascalize .Name }}API
    52  	{{ end -}}
    53  	Logger func(string, ...interface{})
    54  	// InnerMiddleware is for the handler executors. These do not apply to the swagger.json document.
    55  	// The middleware executes after routing but before authentication, binding and validation
    56  	InnerMiddleware func(http.Handler) http.Handler
    57  
    58  	// Authorizer is used to authorize a request after the Auth function was called using the "Auth*" functions
    59  	// and the principal was stored in the context in the "AuthKey" context value.
    60  	Authorizer func(*http.Request) error
    61  
    62  	{{ range .SecurityDefinitions -}}
    63  	{{ if .IsBasicAuth -}}
    64  	// Auth{{ pascalize .ID }} for basic authentication
    65    Auth{{ pascalize .ID }} func(user string, pass string) ({{ if .PrincipalIsNullable }}*{{ end }}{{ .Principal }}, error)
    66  	{{ end -}}
    67  	{{ if .IsAPIKeyAuth -}}
    68  	// Auth{{ pascalize .ID }} Applies when the "{{ .Name }}" {{ .Source }} is set
    69    Auth{{ pascalize .ID }} func(token string) ({{ if .PrincipalIsNullable }}*{{ end }}{{ .Principal }}, error)
    70  	{{ end }}
    71  	{{ if .IsOAuth2 -}}
    72  	// Auth{{ pascalize .ID }} For OAuth2 authentication
    73    Auth{{ pascalize .ID }} func(token string, scopes []string) ({{ if .PrincipalIsNullable }}*{{ end }}{{ .Principal }}, error)
    74  	{{ end -}}
    75  	{{ end -}}
    76  
    77  	// Authenticator to use for all APIKey authentication
    78  	APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator
    79  	// Authenticator to use for all Bearer authentication
    80  	BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator
    81  	// Authenticator to use for all Basic authentication
    82  	BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator
    83  
    84  	{{ range .Consumes -}}
    85  	{{ if .Implementation -}}
    86  	// {{ pascalize .Name }}Consumer is a {{ .Name }} consumer that will replace the default if not nil.
    87  	{{ pascalize .Name }}Consumer runtime.Consumer
    88  	{{ end -}}
    89  	{{ end -}}
    90  }
    91  
    92  // Handler returns an http.Handler given the handler configuration
    93  // It mounts all the business logic implementers in the right routing.
    94  func Handler(c Config) (http.Handler, error) {
    95  	h, _, err := HandlerAPI(c)
    96  	return h, err
    97  }
    98  
    99  // HandlerAPI returns an http.Handler given the handler configuration
   100  // and the corresponding *{{ pascalize .Name }} instance.
   101  // It mounts all the business logic implementers in the right routing.
   102  func HandlerAPI(c Config) (http.Handler, *{{.Package}}.{{ pascalize .Name }}API, error) {
   103  	spec, err := loads.Analyzed(swaggerCopy(SwaggerJSON), "")
   104  	if err != nil {
   105  		return nil, nil, fmt.Errorf("analyze swagger: %v", err)
   106  	}
   107  	api := {{.Package}}.New{{ pascalize .Name }}API(spec)
   108  	api.ServeError = errors.ServeError
   109  	api.Logger = c.Logger
   110  
   111  	if c.APIKeyAuthenticator != nil {
   112  		api.APIKeyAuthenticator = c.APIKeyAuthenticator
   113  	}
   114  	if c.BasicAuthenticator  != nil {
   115  		api.BasicAuthenticator  = c.BasicAuthenticator
   116  	}
   117  	if c.BearerAuthenticator  != nil {
   118  		api.BearerAuthenticator  = c.BearerAuthenticator
   119  	}
   120  
   121  	{{ range .Consumes -}}
   122  	if c.{{ pascalize .Name }}Consumer != nil {
   123  		api.{{ pascalize .Name }}Consumer = c.{{ pascalize .Name }}Consumer
   124  	} else {
   125  		{{ if .Implementation -}}
   126  		api.{{ pascalize .Name }}Consumer = {{ .Implementation }}
   127  		{{ else }}
   128  		api.{{ pascalize .Name }}Consumer = runtime.ConsumerFunc(func(r io.Reader, target interface{}) error {
   129  			return errors.NotImplemented("{{.Name}} consumer has not yet been implemented")
   130  		})
   131  		{{ end -}}
   132  	}
   133  	{{ end -}}
   134  	{{ range .Produces -}}
   135  	{{ if .Implementation -}}
   136  	api.{{ pascalize .Name }}Producer = {{ .Implementation }}
   137  	{{ else -}}
   138  	api.{{ pascalize .Name }}Producer = runtime.ProducerFunc(func(w io.Writer, data interface{}) error {
   139  		return errors.NotImplemented("{{.Name}} producer has not yet been implemented")
   140  	})
   141  	{{ end -}}
   142  	{{ end -}}
   143  
   144  	{{ range .SecurityDefinitions -}}
   145  	{{ if .IsBasicAuth -}}
   146  	api.{{ pascalize .ID }}Auth = func(user string, pass string) ({{if .PrincipalIsNullable }}*{{ end }}{{.Principal}}, error) {
   147      if c.Auth{{ pascalize .ID }} == nil {
   148       {{- if eq .Principal "interface{}" }}
   149          return "", nil
   150       {{- else }}
   151          panic("you specified a custom principal type, but did not provide the authenticator to provide this")
   152       {{- end }}
   153      }
   154  		return c.Auth{{ pascalize .ID }}(user, pass)
   155  	}
   156  	{{ end -}}
   157  	{{ if .IsAPIKeyAuth -}}
   158  	api.{{ pascalize .ID }}Auth = func(token string) ({{ if .PrincipalIsNullable }}*{{ end }}{{.Principal}}, error) {
   159  	  if c.Auth{{ pascalize .ID }} == nil {
   160       {{- if eq .Principal "interface{}" }}
   161  	      return token, nil
   162       {{- else }}
   163          panic("you specified a custom principal type, but did not provide the authenticator to provide this")
   164       {{- end }}
   165  	  }
   166  		return c.Auth{{ pascalize .ID }}(token)
   167  	}
   168  	{{ end }}
   169  	{{ if .IsOAuth2 -}}
   170  	api.{{ pascalize .ID }}Auth = func(token string, scopes []string) ({{ if .PrincipalIsNullable }}*{{ end }}{{.Principal}}, error) {
   171      if c.Auth{{ pascalize .ID }} == nil {
   172       {{- if eq .Principal "interface{}" }}
   173          return token, nil
   174       {{- else }}
   175          panic("you specified a custom principal type, but did not provide the authenticator to provide this")
   176       {{- end }}
   177      }
   178  		return c.Auth{{ pascalize .ID }}(token, scopes)
   179  	}
   180  	{{ end -}}
   181  	{{ end -}}
   182  
   183  	{{ if .SecurityDefinitions -}}
   184  	api.APIAuthorizer = authorizer(c.Authorizer)
   185  	{{ end -}}
   186  
   187  	{{ range .Operations -}}
   188  	api.{{if ne .Package $package}}{{pascalize .Package}}{{end}}{{ pascalize .Name }}Handler =
   189    {{- .PackageAlias }}.{{ pascalize .Name }}HandlerFunc(func(params {{.PackageAlias}}.{{ pascalize .Name }}Params{{if .Authorized}}, principal {{ if .PrincipalIsNullable }}*{{ end }}{{ .Principal }}{{end}}) middleware.Responder {
   190  		ctx := params.HTTPRequest.Context()
   191  		{{ if .Authorized -}}
   192  		ctx = storeAuth(ctx, principal)
   193  		{{ end -}}
   194  		return c.{{pascalize .Package}}API.{{pascalize .Name}}(ctx, params)
   195  	})
   196  	{{ end -}}
   197  
   198  	api.ServerShutdown = func() {  }
   199  	return api.Serve(c.InnerMiddleware), api, nil
   200  }
   201  
   202  // swaggerCopy copies the swagger json to prevent data races in runtime
   203  func swaggerCopy(orig json.RawMessage) json.RawMessage {
   204  	c := make(json.RawMessage, len(orig))
   205  	copy(c, orig)
   206  	return c
   207  }
   208  
   209  // authorizer is a helper function to implement the runtime.Authorizer interface.
   210  type authorizer func(*http.Request) error
   211  
   212  func (a authorizer) Authorize(req *http.Request, principal interface{}) error {
   213  	if a == nil {
   214  		return nil
   215  	}
   216  	ctx := storeAuth(req.Context(), principal)
   217  	return a(req.WithContext(ctx))
   218  }
   219  
   220  func storeAuth(ctx context.Context, principal interface{}) context.Context {
   221  	return context.WithValue(ctx, AuthKey, principal)
   222  }