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