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