github.com/kaisawind/go-swagger@v0.19.0/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  	{{range .DefaultImports}}{{printf "%q" .}}
    23  	{{end}}
    24  	{{range $key, $value := .Imports}}{{$key}} {{ printf "%q" $value}}
    25  	{{end}}
    26  )
    27  {{ $package := .Package }}
    28  
    29  type contextKey string
    30  
    31  const AuthKey contextKey = "Auth"
    32  
    33  {{ range .OperationGroups -}}
    34  //go:generate mockery -name {{ pascalize .Name}}API -inpkg
    35  
    36  // {{ pascalize .Name }}API {{ .Description }}
    37  type {{ pascalize .Name }}API interface {
    38  {{ range .Operations -}}
    39  	{{ if .Description -}}
    40  	// {{ pascalize .Name }} is {{ .Description }}
    41  	{{ end -}}
    42  	{{ pascalize .Name }}(ctx context.Context, params {{.Package}}.{{ pascalize .Name }}Params) middleware.Responder
    43  {{ end -}}
    44  }
    45  {{ end }}
    46  
    47  // Config is configuration for Handler
    48  type Config struct {
    49  	{{ range .OperationGroups -}}
    50  	{{ pascalize .Name }}API
    51  	{{ end -}}
    52  	Logger func(string, ...interface{})
    53  	// InnerMiddleware is for the handler executors. These do not apply to the swagger.json document.
    54  	// The middleware executes after routing but before authentication, binding and validation
    55  	InnerMiddleware func(http.Handler) http.Handler
    56  
    57  	// Authorizer is used to authorize a request after the Auth function was called using the "Auth*" functions
    58  	// and the principal was stored in the context in the "AuthKey" context value.
    59  	Authorizer func(*http.Request) error
    60  
    61  	{{ range .SecurityDefinitions -}}
    62  	{{ if .IsBasicAuth -}}
    63  	// Auth{{ pascalize .ID }} for basic authentication
    64  	Auth{{ pascalize .ID }} func(user string, pass string)
    65  	{{ end -}}
    66  	{{ if .IsAPIKeyAuth -}}
    67  	// Auth{{ pascalize .ID }} Applies when the "{{ .Name }}" {{ .Source }} is set
    68  	Auth{{ pascalize .ID }} func(token string) (interface{}, error)
    69  	{{ end }}
    70  	{{ if .IsOAuth2 -}}
    71  	// Auth{{ pascalize .ID }} For OAuth2 authentication
    72  	Auth{{ pascalize .ID }} func(token string, scopes []string) (interface{}, error)
    73  	{{ end -}}
    74  	{{ end -}}
    75  }
    76  
    77  // Handler returns an http.Handler given the handler configuration
    78  // It mounts all the business logic implementers in the right routing.
    79  func Handler(c Config) (http.Handler, error) {
    80  	h, _, err := HandlerAPI(c)
    81  	return h, err
    82  }
    83  
    84  // HandlerAPI returns an http.Handler given the handler configuration
    85  // and the corresponding *{{ pascalize .Name }} instance.
    86  // It mounts all the business logic implementers in the right routing.
    87  func HandlerAPI(c Config) (http.Handler, *{{.Package}}.{{ pascalize .Name }}API, error) {
    88  	spec, err := loads.Analyzed(swaggerCopy(SwaggerJSON), "")
    89  	if err != nil {
    90  		return nil, nil, fmt.Errorf("analyze swagger: %v", err)
    91  	}
    92  	api := {{.Package}}.New{{ pascalize .Name }}API(spec)
    93  	api.ServeError = errors.ServeError
    94  	api.Logger = c.Logger
    95  
    96  	{{ range .Consumes -}}
    97  	{{ if .Implementation -}}
    98  	api.{{ pascalize .Name }}Consumer = {{ .Implementation }}
    99  	{{ else }}
   100  	api.{{ pascalize .Name }}Consumer = runtime.ConsumerFunc(func(r io.Reader, target interface{}) error {
   101  		return errors.NotImplemented("{{.Name}} consumer has not yet been implemented")
   102  	})
   103  	{{ end -}}
   104  	{{ end -}}
   105  	{{ range .Produces -}}
   106  	{{ if .Implementation -}}
   107  	api.{{ pascalize .Name }}Producer = {{ .Implementation }}
   108  	{{ else -}}
   109  	api.{{ pascalize .Name }}Producer = runtime.ProducerFunc(func(w io.Writer, data interface{}) error {
   110  		return errors.NotImplemented("{{.Name}} producer has not yet been implemented")
   111  	})
   112  	{{ end -}}
   113  	{{ end -}}
   114  
   115  	{{ range .SecurityDefinitions -}}
   116  	{{ if .IsBasicAuth -}}
   117  	api.{{ pascalize .ID }}Auth = func(user string, pass string) ({{if not ( eq .Principal "interface{}" )}}*{{ end }}{{.Principal}}, error) {
   118          if c.Auth{{ pascalize .ID }} == nil {
   119              return "", nil
   120          }
   121  		return c.Auth{{ pascalize .ID }}(user, pass)
   122  	}
   123  	{{ end -}}
   124  	{{ if .IsAPIKeyAuth -}}
   125  	api.{{ pascalize .ID }}Auth = func(token string) ({{if not ( eq .Principal "interface{}" )}}*{{ end }}{{.Principal}}, error) {
   126  	    if c.Auth{{ pascalize .ID }} == nil {
   127  	        return token, nil
   128  	    }
   129  		return c.Auth{{ pascalize .ID }}(token)
   130  	}
   131  	{{ end }}
   132  	{{ if .IsOAuth2 -}}
   133  	api.{{ pascalize .ID }}Auth = func(token string, scopes []string) ({{if not ( eq .Principal "interface{}" )}}*{{ end }}{{.Principal}}, error) {
   134          if c.Auth{{ pascalize .ID }} == nil {
   135              return token, nil
   136          }
   137  		return c.Auth{{ pascalize .ID }}(token, scopes)
   138  	}
   139  	{{ end -}}
   140  	{{ end -}}
   141  
   142  	{{ if .SecurityDefinitions -}}
   143  	api.APIAuthorizer = authorizer(c.Authorizer)
   144  	{{ end -}}
   145  
   146  	{{ range .Operations -}}
   147  	api.{{if ne .Package $package}}{{pascalize .Package}}{{end}}{{ pascalize .Name }}Handler = {{.Package}}.{{ pascalize .Name }}HandlerFunc(func(params {{.Package}}.{{ pascalize .Name }}Params{{if .Authorized}}, principal interface{}{{end}}) middleware.Responder {
   148  		ctx := params.HTTPRequest.Context()
   149  		{{ if .Authorized -}}
   150  		ctx = storeAuth(ctx, principal)
   151  		{{ end -}}
   152  		return c.{{pascalize .Package}}API.{{pascalize .Name}}(ctx, params)
   153  	})
   154  	{{ end -}}
   155  
   156  	api.ServerShutdown = func() {  }
   157  	return api.Serve(c.InnerMiddleware), api, nil
   158  }
   159  
   160  // swaggerCopy copies the swagger json to prevent data races in runtime
   161  func swaggerCopy(orig json.RawMessage) json.RawMessage {
   162  	c := make(json.RawMessage, len(orig))
   163  	copy(c, orig)
   164  	return c
   165  }
   166  
   167  // authorizer is a helper function to implement the runtime.Authorizer interface.
   168  type authorizer func(*http.Request) error
   169  
   170  func (a authorizer) Authorize(req *http.Request, principal interface{}) error {
   171  	if a == nil {
   172  		return nil
   173  	}
   174  	ctx := storeAuth(req.Context(), principal)
   175  	return a(req.WithContext(ctx))
   176  }
   177  
   178  func storeAuth(ctx context.Context, principal interface{}) context.Context {
   179  	return context.WithValue(ctx, AuthKey, principal)
   180  }