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

     1  // This file is safe to edit. Once it exists it will not be overwritten
     2  
     3  {{ if .Copyright -}}// {{ comment .Copyright -}}{{ end }}
     4  
     5  
     6  package {{ .APIPackage }}
     7  
     8  import (
     9    "context"
    10    "crypto/tls"
    11    "io"
    12    "log"
    13    "net/http"
    14  
    15    "github.com/go-openapi/errors"
    16    "github.com/go-openapi/runtime"
    17    "github.com/go-openapi/runtime/middleware"
    18    "github.com/go-openapi/runtime/security"
    19  
    20    {{ imports .DefaultImports }}
    21    {{ imports .Imports }}
    22  )
    23  
    24  {{ with .GenOpts }}
    25  //go:generate swagger generate server --target {{ .TargetPath }} --name {{ .Name }} --spec {{ .SpecPath }}
    26  {{- if .APIPackage }}{{ if ne .APIPackage "operations" }} --api-package {{ .APIPackage }}{{ end }}{{ end }}
    27  {{- if .ModelPackage }}{{ if ne .ModelPackage "models" }} --model-package {{ .ModelPackage }}{{ end }}{{ end }}
    28  {{- if .ServerPackage }}{{ if ne .ServerPackage "restapi"}} --server-package {{ .ServerPackage }}{{ end }}{{ end }}
    29  {{- if .ClientPackage }}{{ if ne .ClientPackage "client" }} --client-package {{ .ClientPackage }}{{ end }}{{ end }}
    30  {{- if .TemplateDir }} --template-dir {{ .TemplateDir }}{{ end }}
    31  {{- range .Operations }} --operation {{ . }}{{ end }}
    32  {{- range .Tags }} --tags {{ . }}{{ end }}
    33  {{- if .Principal }} --principal {{ .Principal }}{{ end }}
    34  {{- if .DefaultScheme }}{{ if ne .DefaultScheme "http" }} --default-scheme {{ .DefaultScheme }}{{ end }}{{ end }}
    35  {{- range .Models }} --model {{ . }}{{ end }}
    36  {{- if or (not .IncludeModel) (not .IncludeValidator) }} --skip-models{{ end }}
    37  {{- if or (not .IncludeHandler) (not .IncludeParameters ) (not .IncludeResponses) }} --skip-operations{{ end }}
    38  {{- if not .IncludeSupport }} --skip-support{{ end }}
    39  {{- if not .IncludeMain }} --exclude-main{{ end }}
    40  {{- if .ExcludeSpec }} --exclude-spec{{ end }}
    41  {{- if .DumpData }} --dump-data{{ end }}
    42  {{- if .StrictResponders }} --strict-responders{{ end }}
    43  {{ end }}
    44  func configureFlags(api *{{.APIPackageAlias}}.{{ pascalize .Name }}API) {
    45    // api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }
    46  }
    47  
    48  func configureAPI(api *{{.APIPackageAlias}}.{{ pascalize .Name }}API) http.Handler {
    49    // configure the api here
    50    api.ServeError = errors.ServeError
    51  
    52    // Set your custom logger if needed. Default one is log.Printf
    53    // Expected interface func(string, ...interface{})
    54    //
    55    // Example:
    56    // api.Logger = log.Printf
    57  
    58    api.UseSwaggerUI()
    59    // To continue using redoc as your UI, uncomment the following line
    60    // api.UseRedoc()
    61  
    62    {{ range .Consumes }}
    63      {{- if .Implementation }}
    64    api.{{ pascalize .Name }}Consumer = {{ .Implementation }}
    65      {{- else }}
    66    api.{{ pascalize .Name }}Consumer = runtime.ConsumerFunc(func(r io.Reader, target interface{}) error {
    67      return errors.NotImplemented("{{.Name}} consumer has not yet been implemented")
    68    })
    69      {{- end }}
    70    {{- end }}
    71    {{ range .Produces }}
    72      {{- if .Implementation }}
    73    api.{{ pascalize .Name }}Producer = {{ .Implementation }}
    74      {{- else }}
    75    api.{{ pascalize .Name }}Producer = runtime.ProducerFunc(func(w io.Writer, data interface{}) error {
    76      return errors.NotImplemented("{{.Name}} producer has not yet been implemented")
    77    })
    78      {{- end }}
    79    {{- end}}
    80    {{ range .SecurityDefinitions }}
    81      {{- if .IsBasicAuth }}
    82    // Applies when the Authorization header is set with the Basic scheme
    83    if api.{{ pascalize .ID }}Auth == nil {
    84    api.{{ pascalize .ID }}Auth = func(user string, pass string) ({{ if .PrincipalIsNullable }}*{{ end }}{{.Principal}}, error) {
    85        return nil, errors.NotImplemented("basic auth  ({{ .ID }}) has not yet been implemented")
    86      }
    87    }
    88      {{- else if .IsAPIKeyAuth }}
    89    // Applies when the "{{ .Name }}" {{ .Source }} is set
    90    if api.{{ pascalize .ID }}Auth == nil {
    91    api.{{ pascalize .ID }}Auth = func(token string) ({{ if .PrincipalIsNullable }}*{{ end }}{{.Principal}}, error) {
    92        return nil, errors.NotImplemented("api key auth ({{ .ID }}) {{.Name}} from {{.Source}} param [{{ .Name }}] has not yet been implemented")
    93      }
    94    }
    95      {{- else if .IsOAuth2 }}
    96      if api.{{ pascalize .ID }}Auth == nil {
    97      api.{{ pascalize .ID }}Auth = func(token string, scopes []string) ({{ if .PrincipalIsNullable }}*{{ end }}{{.Principal}}, error) {
    98        return nil, errors.NotImplemented("oauth2 bearer auth ({{ .ID }}) has not yet been implemented")
    99      }
   100    }
   101      {{- end }}
   102    {{- end }}
   103    {{- if .SecurityDefinitions }}
   104  
   105    // Set your custom authorizer if needed. Default one is security.Authorized()
   106    // Expected interface runtime.Authorizer
   107    //
   108    // Example:
   109    // api.APIAuthorizer = security.Authorized()
   110    {{- end }}
   111    {{- $package := .Package }}
   112    {{- $apipackagealias := .APIPackageAlias }}
   113    {{- range .Operations }}
   114      {{- if .HasFormParams }}
   115    // You may change here the memory limit for this multipart form parser. Below is the default (32 MB).
   116    // {{ if ne .Package $package }}{{ .PackageAlias }}{{ else }}{{ $apipackagealias }}{{ end }}.{{ pascalize .Name }}MaxParseMemory = 32 << 20
   117      {{- end }}
   118    {{- end }}
   119    {{ range .Operations }}
   120    if api.{{ if ne .Package $package }}{{ pascalize .Package }}{{ end }}{{ pascalize .Name }}Handler == nil {
   121      api.{{ if ne .Package $package }}{{pascalize .Package}}{{ end }}{{ pascalize .Name }}Handler =
   122      {{- if ne .Package $package }}
   123        {{- .PackageAlias }}.{{- pascalize .Name }}HandlerFunc(func(params {{ .PackageAlias }}.{{- pascalize .Name }}Params
   124      {{- else }}
   125        {{- $apipackagealias }}.{{- pascalize .Name }}HandlerFunc(func(params {{ $apipackagealias }}.{{- pascalize .Name }}Params
   126      {{- end }}
   127    {{- if $.GenOpts.StrictResponders }}
   128      {{- if .Authorized}}, principal {{ if .PrincipalIsNullable }}*{{ end }}{{.Principal}}{{end}}) {{.Package}}.{{ pascalize .Name }}Responder {
   129       return {{.Package}}.{{ pascalize .Name }}NotImplemented()
   130    {{ else }}
   131      {{- if .Authorized}}, principal {{if .PrincipalIsNullable }}*{{ end }}{{.Principal}}{{end}}) middleware.Responder {
   132        return middleware.NotImplemented("operation {{ .Package}}.{{pascalize .Name}} has not yet been implemented")
   133    {{ end -}}
   134      })
   135    }
   136    {{- end }}
   137  
   138    api.PreServerShutdown = func() {  }
   139  
   140    api.ServerShutdown = func() {  }
   141  
   142    return setupGlobalMiddleware(api.Serve(setupMiddlewares))
   143  }
   144  
   145  // The TLS configuration before HTTPS server starts.
   146  func configureTLS(tlsConfig *tls.Config) {
   147    // Make all necessary changes to the TLS configuration here.
   148  }
   149  
   150  // As soon as server is initialized but not run yet, this function will be called.
   151  // If you need to modify a config, store server instance to stop it individually later, this is the place.
   152  // This function can be called multiple times, depending on the number of serving schemes.
   153  // scheme value will be set accordingly: "http", "https" or "unix".
   154  func configureServer(s *http.Server, scheme, addr string) {
   155  }
   156  
   157  // The middleware configuration is for the handler executors. These do not apply to the swagger.json document.
   158  // The middleware executes after routing but before authentication, binding and validation.
   159  func setupMiddlewares(handler http.Handler) http.Handler {
   160  	return handler
   161  }
   162  
   163  // The middleware configuration happens before anything, this middleware also applies to serving the swagger.json document.
   164  // So this is a good place to plug in a panic handling middleware, logging and metrics.
   165  func setupGlobalMiddleware(handler http.Handler) http.Handler {
   166  	return handler
   167  }