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