github.com/kaisawind/go-swagger@v0.19.0/generator/templates/server/builder.gotmpl (about) 1 // Code generated by go-swagger; DO NOT EDIT. 2 3 4 {{ if .Copyright -}}// {{ comment .Copyright -}}{{ end }} 5 6 7 package {{.Package}} 8 {{ $package := .Package }} 9 10 // This file was generated by the swagger tool. 11 // Editing this file might prove futile when you re-run the swagger generate command 12 13 import ( 14 "context" 15 "strings" 16 "net/http" 17 18 "github.com/go-openapi/swag" 19 spec "github.com/go-openapi/spec" 20 loads "github.com/go-openapi/loads" 21 errors "github.com/go-openapi/errors" 22 strfmt "github.com/go-openapi/strfmt" 23 runtime "github.com/go-openapi/runtime" 24 middleware "github.com/go-openapi/runtime/middleware" 25 security "github.com/go-openapi/runtime/security" 26 27 {{ range .DefaultImports }}{{ printf "%q" . }} 28 {{ end }} 29 {{ range $key, $value := .Imports }}{{ $key }} {{ printf "%q" $value }} 30 {{ end }} 31 ) 32 33 // New{{ pascalize .Name }}API creates a new {{ pascalize .Name }} instance 34 func New{{ pascalize .Name }}API(spec *loads.Document) *{{ pascalize .Name }}API { 35 return &{{ pascalize .Name }}API{ 36 handlers: make(map[string]map[string]http.Handler), 37 formats: strfmt.Default, 38 defaultConsumes: "{{ .DefaultConsumes }}", 39 defaultProduces: "{{ .DefaultProduces }}", 40 customConsumers: make(map[string]runtime.Consumer), 41 customProducers: make(map[string]runtime.Producer), 42 ServerShutdown: func() { }, 43 spec: spec, 44 ServeError: errors.ServeError, 45 BasicAuthenticator: security.BasicAuth, 46 APIKeyAuthenticator: security.APIKeyAuth, 47 BearerAuthenticator: security.BearerAuth, 48 {{ range .Consumes }}{{ if .Implementation }}{{ pascalize .Name }}Consumer: {{ .Implementation }},{{else}}{{ pascalize .Name }}Consumer: runtime.ConsumerFunc(func(r io.Reader, target interface{}) error { 49 return errors.NotImplemented("{{.Name}} consumer has not yet been implemented") 50 }),{{end}} 51 {{end}}{{ range .Produces }}{{ if .Implementation }}{{ pascalize .Name }}Producer: {{ .Implementation }},{{else}}{{ pascalize .Name }}Producer: runtime.ProducerFunc(func(w io.Writer, data interface{}) error { 52 return errors.NotImplemented("{{.Name}} producer has not yet been implemented") 53 }),{{end}} 54 {{end}}{{range .Operations}}{{if ne .Package $package}}{{ pascalize .Package }}{{end}}{{ pascalize .Name }}Handler: {{if ne .Package $package}}{{ .Package }}.{{end}}{{ pascalize .Name }}HandlerFunc(func(params {{if ne .Package $package}}{{ .Package }}.{{end}}{{ pascalize .Name }}Params{{if .Authorized}}, principal {{if not ( eq .Principal "interface{}" )}}*{{ end }}{{.Principal}}{{end}}) middleware.Responder { 55 return middleware.NotImplemented("operation {{if ne .Package $package}}{{ pascalize .Package }}{{end}}{{pascalize .Name}} has not yet been implemented") 56 }), 57 {{end}} 58 {{range .SecurityDefinitions}}{{if .IsBasicAuth}}// Applies when the Authorization header is set with the Basic scheme 59 {{ pascalize .ID }}Auth: func(user string, pass string) ({{if not ( eq .Principal "interface{}" )}}*{{ end }}{{.Principal}}, error) { 60 return nil, errors.NotImplemented("basic auth ({{ .ID }}) has not yet been implemented") 61 }, 62 {{end}}{{if .IsAPIKeyAuth}}// Applies when the "{{ .Name }}" {{ .Source }} is set 63 {{ pascalize .ID }}Auth: func(token string) ({{if not ( eq .Principal "interface{}" )}}*{{ end }}{{.Principal}}, error) { 64 return nil, errors.NotImplemented("api key auth ({{ .ID }}) {{.Name}} from {{.Source}} param [{{ .Name }}] has not yet been implemented") 65 },{{end}}{{if .IsOAuth2}}{{ pascalize .ID }}Auth: func(token string, scopes []string) ({{if not ( eq .Principal "interface{}" )}}*{{ end }}{{.Principal}}, error) { 66 return nil, errors.NotImplemented("oauth2 bearer auth ({{ .ID }}) has not yet been implemented") 67 }, 68 {{end}} 69 {{end}} 70 {{if .SecurityDefinitions}} 71 // default authorizer is authorized meaning no requests are blocked 72 APIAuthorizer: security.Authorized(), 73 {{end}} 74 } 75 } 76 77 /*{{ pascalize .Name }}API {{ if .Info }}{{ if .Info.Description }}{{.Info.Description}}{{ else }}the {{ humanize .Name }} API{{ end }}{{ end }} */ 78 type {{ pascalize .Name }}API struct { 79 spec *loads.Document 80 context *middleware.Context 81 handlers map[string]map[string]http.Handler 82 formats strfmt.Registry 83 customConsumers map[string]runtime.Consumer 84 customProducers map[string]runtime.Producer 85 defaultConsumes string 86 defaultProduces string 87 Middleware func(middleware.Builder) http.Handler 88 89 // BasicAuthenticator generates a runtime.Authenticator from the supplied basic auth function. 90 // It has a default implementation in the security package, however you can replace it for your particular usage. 91 BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator 92 // APIKeyAuthenticator generates a runtime.Authenticator from the supplied token auth function. 93 // It has a default implementation in the security package, however you can replace it for your particular usage. 94 APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator 95 // BearerAuthenticator generates a runtime.Authenticator from the supplied bearer token auth function. 96 // It has a default implementation in the security package, however you can replace it for your particular usage. 97 BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator 98 99 {{range .Consumes}}// {{ pascalize .Name }}Consumer registers a consumer for a "{{ .MediaType }}" mime type 100 {{ pascalize .Name }}Consumer runtime.Consumer 101 {{end}} 102 {{range .Produces}}// {{ pascalize .Name }}Producer registers a producer for a "{{ .MediaType }}" mime type 103 {{ pascalize .Name }}Producer runtime.Producer 104 {{end}} 105 {{range .SecurityDefinitions}} 106 {{if .IsBasicAuth}}// {{ pascalize .ID }}Auth registers a function that takes username and password and returns a principal 107 // it performs authentication with basic auth 108 {{ pascalize .ID }}Auth func(string, string) ({{ if not ( eq .Principal "interface{}" ) }}*{{ end }}{{ .Principal }}, error) 109 {{end}}{{if .IsAPIKeyAuth}}// {{ pascalize .ID }}Auth registers a function that takes a token and returns a principal 110 // it performs authentication based on an api key {{ .Name }} provided in the {{.Source}} 111 {{ pascalize .ID }}Auth func(string) ({{ if not ( eq .Principal "interface{}" ) }}*{{ end }}{{ .Principal }}, error) 112 {{end}}{{ if .IsOAuth2 }}// {{ pascalize .ID }}Auth registers a function that takes an access token and a collection of required scopes and returns a principal 113 // it performs authentication based on an oauth2 bearer token provided in the request 114 {{ pascalize .ID }}Auth func(string, []string) ({{ if not ( eq .Principal "interface{}" ) }}*{{ end }}{{ .Principal }}, error) 115 {{ end }} 116 {{end}} 117 {{if .SecurityDefinitions}} 118 // APIAuthorizer provides access control (ACL/RBAC/ABAC) by providing access to the request and authenticated principal 119 APIAuthorizer runtime.Authorizer 120 {{end}} 121 {{range .Operations}}// {{if ne .Package $package}}{{ pascalize .Package }}{{end}}{{ pascalize .Name }}Handler sets the operation handler for the {{ humanize .Name }} operation 122 {{if ne .Package $package}}{{ pascalize .Package }}{{end}}{{ pascalize .Name }}Handler {{if ne .Package $package}}{{.Package}}.{{end}}{{ pascalize .Name }}Handler 123 {{end}} 124 // ServeError is called when an error is received, there is a default handler 125 // but you can set your own with this 126 ServeError func(http.ResponseWriter, *http.Request, error) 127 128 // ServerShutdown is called when the HTTP(S) server is shut down and done 129 // handling all active connections and does not accept connections any more 130 ServerShutdown func() 131 132 // Custom command line argument groups with their descriptions 133 CommandLineOptionsGroups []swag.CommandLineOptionsGroup 134 135 // User defined logger function. 136 Logger func(string, ...interface{}) 137 } 138 139 // SetDefaultProduces sets the default produces media type 140 func ({{.ReceiverName}} *{{ pascalize .Name }}API) SetDefaultProduces(mediaType string) { 141 {{.ReceiverName}}.defaultProduces = mediaType 142 } 143 144 // SetDefaultConsumes returns the default consumes media type 145 func ({{.ReceiverName}} *{{ pascalize .Name }}API) SetDefaultConsumes(mediaType string) { 146 {{.ReceiverName}}.defaultConsumes = mediaType 147 } 148 149 // SetSpec sets a spec that will be served for the clients. 150 func ({{.ReceiverName}} *{{ pascalize .Name }}API) SetSpec(spec *loads.Document) { 151 {{.ReceiverName}}.spec = spec 152 } 153 154 // DefaultProduces returns the default produces media type 155 func ({{.ReceiverName}} *{{ pascalize .Name }}API) DefaultProduces() string { 156 return {{.ReceiverName}}.defaultProduces 157 } 158 159 // DefaultConsumes returns the default consumes media type 160 func ({{.ReceiverName}} *{{ pascalize .Name }}API) DefaultConsumes() string { 161 return {{.ReceiverName}}.defaultConsumes 162 } 163 164 // Formats returns the registered string formats 165 func ({{.ReceiverName}} *{{ pascalize .Name }}API) Formats() strfmt.Registry { 166 return {{.ReceiverName}}.formats 167 } 168 169 // RegisterFormat registers a custom format validator 170 func ({{.ReceiverName}} *{{ pascalize .Name }}API) RegisterFormat(name string, format strfmt.Format, validator strfmt.Validator) { 171 {{.ReceiverName}}.formats.Add(name, format, validator) 172 } 173 174 // Validate validates the registrations in the {{ pascalize .Name }}API 175 func ({{.ReceiverName}} *{{ pascalize .Name }}API) Validate() error { 176 var unregistered []string 177 {{range .Consumes}} 178 if {{.ReceiverName}}.{{ pascalize .Name }}Consumer == nil { 179 unregistered = append(unregistered, "{{ pascalize .Name }}Consumer") 180 } 181 {{end}} 182 {{range .Produces}} 183 if {{.ReceiverName}}.{{ pascalize .Name }}Producer == nil { 184 unregistered = append(unregistered, "{{ pascalize .Name }}Producer") 185 } 186 {{end}} 187 {{range .SecurityDefinitions}} 188 if {{.ReceiverName}}.{{ pascalize .ID }}Auth == nil { 189 unregistered = append(unregistered, "{{if .IsAPIKeyAuth }}{{ pascalize .Name }}{{ else }}{{ pascalize .ID }}{{ end }}Auth") 190 } 191 {{end}} 192 {{range .Operations}} 193 if {{.ReceiverName}}.{{if ne .Package $package}}{{ pascalize .Package }}{{end}}{{ pascalize .Name }}Handler == nil { 194 unregistered = append(unregistered, "{{if ne .Package $package}}{{.Package}}.{{end}}{{ pascalize .Name }}Handler") 195 } 196 {{end}} 197 198 if len(unregistered) > 0 { 199 return fmt.Errorf("missing registration: %s", strings.Join(unregistered, ", ")) 200 } 201 202 return nil 203 } 204 // ServeErrorFor gets a error handler for a given operation id 205 func ({{.ReceiverName}} *{{ pascalize .Name }}API) ServeErrorFor(operationID string) func(http.ResponseWriter, *http.Request, error) { 206 return {{.ReceiverName}}.ServeError 207 } 208 // AuthenticatorsFor gets the authenticators for the specified security schemes 209 func ({{.ReceiverName}} *{{ pascalize .Name }}API) AuthenticatorsFor(schemes map[string]spec.SecurityScheme) map[string]runtime.Authenticator { 210 {{if .SecurityDefinitions}} 211 result := make(map[string]runtime.Authenticator) 212 for name, scheme := range schemes { 213 switch name { 214 {{range .SecurityDefinitions}} 215 case "{{.ID}}": 216 {{if .IsBasicAuth}}_ = scheme 217 result[name] = {{.ReceiverName}}.BasicAuthenticator({{ if not ( eq .Principal "interface{}" ) }}func(username, password string) (interface{}, error) { 218 return {{ end }}{{.ReceiverName}}.{{ pascalize .ID }}Auth{{ if not ( eq .Principal "interface{}" ) }}(username, password) 219 }{{ end }}){{end}} 220 {{if .IsAPIKeyAuth}}result[name] = {{.ReceiverName}}.APIKeyAuthenticator(scheme.Name, scheme.In, {{ if not ( eq .Principal "interface{}" ) }}func(token string) (interface{}, error) { 221 return {{ end }}{{.ReceiverName}}.{{ pascalize .ID }}Auth{{ if not ( eq .Principal "interface{}" ) }}(token) 222 }{{ end }}){{end}} 223 {{if .IsOAuth2}}result[name] = {{.ReceiverName}}.BearerAuthenticator(scheme.Name, {{ if not ( eq .Principal "interface{}" ) }}func(token string, scopes []string) (interface{}, error) { 224 return {{ end }}{{.ReceiverName}}.{{ pascalize .ID }}Auth{{ if not ( eq .Principal "interface{}" ) }}(token, scopes) 225 }{{ end }}){{end}} 226 {{end}} 227 } 228 } 229 return result 230 {{else}} 231 return nil 232 {{end}} 233 } 234 235 // Authorizer returns the registered authorizer 236 func ({{.ReceiverName}} *{{ pascalize .Name }}API) Authorizer() runtime.Authorizer { 237 {{if .SecurityDefinitions}} 238 return {{.ReceiverName}}.APIAuthorizer 239 {{else}} 240 return nil 241 {{end}} 242 } 243 244 // ConsumersFor gets the consumers for the specified media types 245 func ({{.ReceiverName}} *{{ pascalize .Name }}API) ConsumersFor(mediaTypes []string) map[string]runtime.Consumer { 246 {{if .Consumes}} 247 result := make(map[string]runtime.Consumer) 248 for _, mt := range mediaTypes { 249 switch mt { 250 {{range .Consumes}} 251 {{range .AllSerializers}} 252 case "{{ mediaTypeName .MediaType }}": 253 result["{{ mediaTypeName .MediaType }}"] = {{.ReceiverName}}.{{ pascalize .Name }}Consumer 254 {{end}} 255 {{end}} 256 } 257 258 if c, ok := {{.ReceiverName}}.customConsumers[mt]; ok { 259 result[mt] = c 260 } 261 } 262 return result 263 {{else}} 264 return nil 265 {{end}} 266 } 267 268 // ProducersFor gets the producers for the specified media types 269 func ({{.ReceiverName}} *{{ pascalize .Name }}API) ProducersFor(mediaTypes []string) map[string]runtime.Producer { 270 {{if .Produces}} 271 result := make(map[string]runtime.Producer) 272 for _, mt := range mediaTypes { 273 switch mt { 274 {{range .Produces}} 275 {{range .AllSerializers}} 276 case "{{ mediaTypeName .MediaType }}": 277 result["{{ mediaTypeName .MediaType }}"] = {{.ReceiverName}}.{{ pascalize .Name }}Producer 278 {{end}} 279 {{end}} 280 } 281 282 if p, ok := {{.ReceiverName}}.customProducers[mt]; ok { 283 result[mt] = p 284 } 285 } 286 return result 287 {{else}} 288 return nil 289 {{end}} 290 } 291 292 // HandlerFor gets a http.Handler for the provided operation method and path 293 func ({{.ReceiverName}} *{{ pascalize .Name }}API) HandlerFor(method, path string) (http.Handler, bool) { 294 if {{.ReceiverName}}.handlers == nil { 295 return nil, false 296 } 297 um := strings.ToUpper(method) 298 if _, ok := {{.ReceiverName}}.handlers[um]; !ok { 299 return nil, false 300 } 301 if path == "/" { 302 path = "" 303 } 304 h, ok := {{.ReceiverName}}.handlers[um][path] 305 return h, ok 306 } 307 308 // Context returns the middleware context for the {{ humanize .Name }} API 309 func ({{.ReceiverName}} *{{ pascalize .Name }}API) Context() *middleware.Context { 310 if {{.ReceiverName}}.context == nil { 311 {{.ReceiverName}}.context = middleware.NewRoutableContext({{.ReceiverName}}.spec, {{.ReceiverName}}, nil) 312 } 313 314 return {{ .ReceiverName }}.context 315 } 316 317 func ({{.ReceiverName}} *{{ pascalize .Name }}API) initHandlerCache() { 318 {{.ReceiverName}}.Context() // don't care about the result, just that the initialization happened 319 {{if .Operations}} 320 if {{ .ReceiverName }}.handlers == nil { 321 {{.ReceiverName}}.handlers = make(map[string]map[string]http.Handler) 322 } 323 {{range .Operations}} 324 if {{ .ReceiverName }}.handlers[{{ printf "%q" (upper .Method) }}] == nil { 325 {{ .ReceiverName }}.handlers[{{ printf "%q" (upper .Method) }}] = make(map[string]http.Handler) 326 } 327 {{.ReceiverName}}.handlers[{{ printf "%q" (upper .Method) }}][{{ if eq .Path "/" }}""{{ else }}{{ printf "%q" (cleanPath .Path) }}{{ end }}] = {{if ne .Package $package}}{{.Package}}.{{end}}New{{ pascalize .Name }}({{.ReceiverName}}.context, {{.ReceiverName}}.{{if ne .Package $package}}{{ pascalize .Package }}{{end}}{{ pascalize .Name }}Handler) 328 {{end}} 329 {{end}} 330 } 331 332 // Serve creates a http handler to serve the API over HTTP 333 // can be used directly in http.ListenAndServe(":8000", api.Serve(nil)) 334 func ({{.ReceiverName}} *{{ pascalize .Name }}API) Serve(builder middleware.Builder) http.Handler { 335 {{ .ReceiverName }}.Init() 336 337 if {{ .ReceiverName}}.Middleware != nil { 338 return {{ .ReceiverName }}.Middleware(builder) 339 } 340 return {{.ReceiverName}}.context.APIHandler(builder) 341 } 342 343 // Init allows you to just initialize the handler cache, you can then recompose the middleware as you see fit 344 func ({{.ReceiverName}} *{{ pascalize .Name }}API) Init() { 345 if len({{.ReceiverName}}.handlers) == 0 { 346 {{.ReceiverName}}.initHandlerCache() 347 } 348 } 349 350 // RegisterConsumer allows you to add (or override) a consumer for a media type. 351 func ({{.ReceiverName}} *{{ pascalize .Name }}API) RegisterConsumer(mediaType string, consumer runtime.Consumer) { 352 {{.ReceiverName}}.customConsumers[mediaType] = consumer 353 } 354 355 // RegisterProducer allows you to add (or override) a producer for a media type. 356 func ({{.ReceiverName}} *{{ pascalize .Name }}API) RegisterProducer(mediaType string, producer runtime.Producer) { 357 {{.ReceiverName}}.customProducers[mediaType] = producer 358 }