github.com/emreu/go-swagger@v0.22.1/examples/todo-list/restapi/operations/todo_list_api.go (about)

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