github.com/circl-dev/go-swagger@v0.31.0/examples/task-tracker/restapi/operations/task_tracker_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/task-tracker/restapi/operations/tasks"
    23  )
    24  
    25  // NewTaskTrackerAPI creates a new TaskTracker instance
    26  func NewTaskTrackerAPI(spec *loads.Document) *TaskTrackerAPI {
    27  	return &TaskTrackerAPI{
    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  		useSwaggerUI:        false,
    38  		ServeError:          errors.ServeError,
    39  		BasicAuthenticator:  security.BasicAuth,
    40  		APIKeyAuthenticator: security.APIKeyAuth,
    41  		BearerAuthenticator: security.BearerAuth,
    42  
    43  		JSONConsumer:          runtime.JSONConsumer(),
    44  		MultipartformConsumer: runtime.DiscardConsumer,
    45  
    46  		JSONProducer: runtime.JSONProducer(),
    47  
    48  		TasksAddCommentToTaskHandler: tasks.AddCommentToTaskHandlerFunc(func(params tasks.AddCommentToTaskParams, principal interface{}) middleware.Responder {
    49  			return middleware.NotImplemented("operation tasks.AddCommentToTask has not yet been implemented")
    50  		}),
    51  		TasksCreateTaskHandler: tasks.CreateTaskHandlerFunc(func(params tasks.CreateTaskParams, principal interface{}) middleware.Responder {
    52  			return middleware.NotImplemented("operation tasks.CreateTask has not yet been implemented")
    53  		}),
    54  		TasksDeleteTaskHandler: tasks.DeleteTaskHandlerFunc(func(params tasks.DeleteTaskParams, principal interface{}) middleware.Responder {
    55  			return middleware.NotImplemented("operation tasks.DeleteTask has not yet been implemented")
    56  		}),
    57  		TasksGetTaskCommentsHandler: tasks.GetTaskCommentsHandlerFunc(func(params tasks.GetTaskCommentsParams) middleware.Responder {
    58  			return middleware.NotImplemented("operation tasks.GetTaskComments has not yet been implemented")
    59  		}),
    60  		TasksGetTaskDetailsHandler: tasks.GetTaskDetailsHandlerFunc(func(params tasks.GetTaskDetailsParams) middleware.Responder {
    61  			return middleware.NotImplemented("operation tasks.GetTaskDetails has not yet been implemented")
    62  		}),
    63  		TasksListTasksHandler: tasks.ListTasksHandlerFunc(func(params tasks.ListTasksParams) middleware.Responder {
    64  			return middleware.NotImplemented("operation tasks.ListTasks has not yet been implemented")
    65  		}),
    66  		TasksUpdateTaskHandler: tasks.UpdateTaskHandlerFunc(func(params tasks.UpdateTaskParams, principal interface{}) middleware.Responder {
    67  			return middleware.NotImplemented("operation tasks.UpdateTask has not yet been implemented")
    68  		}),
    69  		TasksUploadTaskFileHandler: tasks.UploadTaskFileHandlerFunc(func(params tasks.UploadTaskFileParams, principal interface{}) middleware.Responder {
    70  			return middleware.NotImplemented("operation tasks.UploadTaskFile has not yet been implemented")
    71  		}),
    72  
    73  		// Applies when the "token" query is set
    74  		APIKeyAuth: func(token string) (interface{}, error) {
    75  			return nil, errors.NotImplemented("api key auth (api_key) token from query param [token] has not yet been implemented")
    76  		},
    77  		// Applies when the "X-Token" header is set
    78  		TokenHeaderAuth: func(token string) (interface{}, error) {
    79  			return nil, errors.NotImplemented("api key auth (token_header) X-Token from header param [X-Token] has not yet been implemented")
    80  		},
    81  		// default authorizer is authorized meaning no requests are blocked
    82  		APIAuthorizer: security.Authorized(),
    83  	}
    84  }
    85  
    86  /*TaskTrackerAPI This application implements a very simple issue tracker.
    87  It's implemented as an API which is described by this swagger spec document.
    88  
    89  The go-swagger project uses this specification to test the code generation.
    90  This document contains all possible values for a swagger definition.
    91  This means that it exercises the framework relatively well.
    92  */
    93  type TaskTrackerAPI struct {
    94  	spec            *loads.Document
    95  	context         *middleware.Context
    96  	handlers        map[string]map[string]http.Handler
    97  	formats         strfmt.Registry
    98  	customConsumers map[string]runtime.Consumer
    99  	customProducers map[string]runtime.Producer
   100  	defaultConsumes string
   101  	defaultProduces string
   102  	Middleware      func(middleware.Builder) http.Handler
   103  	useSwaggerUI    bool
   104  
   105  	// BasicAuthenticator generates a runtime.Authenticator from the supplied basic auth function.
   106  	// It has a default implementation in the security package, however you can replace it for your particular usage.
   107  	BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator
   108  
   109  	// APIKeyAuthenticator generates a runtime.Authenticator from the supplied token auth function.
   110  	// It has a default implementation in the security package, however you can replace it for your particular usage.
   111  	APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator
   112  
   113  	// BearerAuthenticator generates a runtime.Authenticator from the supplied bearer token auth function.
   114  	// It has a default implementation in the security package, however you can replace it for your particular usage.
   115  	BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator
   116  
   117  	// JSONConsumer registers a consumer for the following mime types:
   118  	//   - application/vnd.goswagger.examples.task-tracker.v1+json
   119  	JSONConsumer runtime.Consumer
   120  	// MultipartformConsumer registers a consumer for the following mime types:
   121  	//   - multipart/form-data
   122  	MultipartformConsumer runtime.Consumer
   123  
   124  	// JSONProducer registers a producer for the following mime types:
   125  	//   - application/vnd.goswagger.examples.task-tracker.v1+json
   126  	JSONProducer runtime.Producer
   127  
   128  	// APIKeyAuth registers a function that takes a token and returns a principal
   129  	// it performs authentication based on an api key token provided in the query
   130  	APIKeyAuth func(string) (interface{}, error)
   131  
   132  	// TokenHeaderAuth registers a function that takes a token and returns a principal
   133  	// it performs authentication based on an api key X-Token provided in the header
   134  	TokenHeaderAuth func(string) (interface{}, error)
   135  
   136  	// APIAuthorizer provides access control (ACL/RBAC/ABAC) by providing access to the request and authenticated principal
   137  	APIAuthorizer runtime.Authorizer
   138  
   139  	// TasksAddCommentToTaskHandler sets the operation handler for the add comment to task operation
   140  	TasksAddCommentToTaskHandler tasks.AddCommentToTaskHandler
   141  	// TasksCreateTaskHandler sets the operation handler for the create task operation
   142  	TasksCreateTaskHandler tasks.CreateTaskHandler
   143  	// TasksDeleteTaskHandler sets the operation handler for the delete task operation
   144  	TasksDeleteTaskHandler tasks.DeleteTaskHandler
   145  	// TasksGetTaskCommentsHandler sets the operation handler for the get task comments operation
   146  	TasksGetTaskCommentsHandler tasks.GetTaskCommentsHandler
   147  	// TasksGetTaskDetailsHandler sets the operation handler for the get task details operation
   148  	TasksGetTaskDetailsHandler tasks.GetTaskDetailsHandler
   149  	// TasksListTasksHandler sets the operation handler for the list tasks operation
   150  	TasksListTasksHandler tasks.ListTasksHandler
   151  	// TasksUpdateTaskHandler sets the operation handler for the update task operation
   152  	TasksUpdateTaskHandler tasks.UpdateTaskHandler
   153  	// TasksUploadTaskFileHandler sets the operation handler for the upload task file operation
   154  	TasksUploadTaskFileHandler tasks.UploadTaskFileHandler
   155  
   156  	// ServeError is called when an error is received, there is a default handler
   157  	// but you can set your own with this
   158  	ServeError func(http.ResponseWriter, *http.Request, error)
   159  
   160  	// PreServerShutdown is called before the HTTP(S) server is shutdown
   161  	// This allows for custom functions to get executed before the HTTP(S) server stops accepting traffic
   162  	PreServerShutdown func()
   163  
   164  	// ServerShutdown is called when the HTTP(S) server is shut down and done
   165  	// handling all active connections and does not accept connections any more
   166  	ServerShutdown func()
   167  
   168  	// Custom command line argument groups with their descriptions
   169  	CommandLineOptionsGroups []swag.CommandLineOptionsGroup
   170  
   171  	// User defined logger function.
   172  	Logger func(string, ...interface{})
   173  }
   174  
   175  // UseRedoc for documentation at /docs
   176  func (o *TaskTrackerAPI) UseRedoc() {
   177  	o.useSwaggerUI = false
   178  }
   179  
   180  // UseSwaggerUI for documentation at /docs
   181  func (o *TaskTrackerAPI) UseSwaggerUI() {
   182  	o.useSwaggerUI = true
   183  }
   184  
   185  // SetDefaultProduces sets the default produces media type
   186  func (o *TaskTrackerAPI) SetDefaultProduces(mediaType string) {
   187  	o.defaultProduces = mediaType
   188  }
   189  
   190  // SetDefaultConsumes returns the default consumes media type
   191  func (o *TaskTrackerAPI) SetDefaultConsumes(mediaType string) {
   192  	o.defaultConsumes = mediaType
   193  }
   194  
   195  // SetSpec sets a spec that will be served for the clients.
   196  func (o *TaskTrackerAPI) SetSpec(spec *loads.Document) {
   197  	o.spec = spec
   198  }
   199  
   200  // DefaultProduces returns the default produces media type
   201  func (o *TaskTrackerAPI) DefaultProduces() string {
   202  	return o.defaultProduces
   203  }
   204  
   205  // DefaultConsumes returns the default consumes media type
   206  func (o *TaskTrackerAPI) DefaultConsumes() string {
   207  	return o.defaultConsumes
   208  }
   209  
   210  // Formats returns the registered string formats
   211  func (o *TaskTrackerAPI) Formats() strfmt.Registry {
   212  	return o.formats
   213  }
   214  
   215  // RegisterFormat registers a custom format validator
   216  func (o *TaskTrackerAPI) RegisterFormat(name string, format strfmt.Format, validator strfmt.Validator) {
   217  	o.formats.Add(name, format, validator)
   218  }
   219  
   220  // Validate validates the registrations in the TaskTrackerAPI
   221  func (o *TaskTrackerAPI) Validate() error {
   222  	var unregistered []string
   223  
   224  	if o.JSONConsumer == nil {
   225  		unregistered = append(unregistered, "JSONConsumer")
   226  	}
   227  	if o.MultipartformConsumer == nil {
   228  		unregistered = append(unregistered, "MultipartformConsumer")
   229  	}
   230  
   231  	if o.JSONProducer == nil {
   232  		unregistered = append(unregistered, "JSONProducer")
   233  	}
   234  
   235  	if o.APIKeyAuth == nil {
   236  		unregistered = append(unregistered, "TokenAuth")
   237  	}
   238  	if o.TokenHeaderAuth == nil {
   239  		unregistered = append(unregistered, "XTokenAuth")
   240  	}
   241  
   242  	if o.TasksAddCommentToTaskHandler == nil {
   243  		unregistered = append(unregistered, "tasks.AddCommentToTaskHandler")
   244  	}
   245  	if o.TasksCreateTaskHandler == nil {
   246  		unregistered = append(unregistered, "tasks.CreateTaskHandler")
   247  	}
   248  	if o.TasksDeleteTaskHandler == nil {
   249  		unregistered = append(unregistered, "tasks.DeleteTaskHandler")
   250  	}
   251  	if o.TasksGetTaskCommentsHandler == nil {
   252  		unregistered = append(unregistered, "tasks.GetTaskCommentsHandler")
   253  	}
   254  	if o.TasksGetTaskDetailsHandler == nil {
   255  		unregistered = append(unregistered, "tasks.GetTaskDetailsHandler")
   256  	}
   257  	if o.TasksListTasksHandler == nil {
   258  		unregistered = append(unregistered, "tasks.ListTasksHandler")
   259  	}
   260  	if o.TasksUpdateTaskHandler == nil {
   261  		unregistered = append(unregistered, "tasks.UpdateTaskHandler")
   262  	}
   263  	if o.TasksUploadTaskFileHandler == nil {
   264  		unregistered = append(unregistered, "tasks.UploadTaskFileHandler")
   265  	}
   266  
   267  	if len(unregistered) > 0 {
   268  		return fmt.Errorf("missing registration: %s", strings.Join(unregistered, ", "))
   269  	}
   270  
   271  	return nil
   272  }
   273  
   274  // ServeErrorFor gets a error handler for a given operation id
   275  func (o *TaskTrackerAPI) ServeErrorFor(operationID string) func(http.ResponseWriter, *http.Request, error) {
   276  	return o.ServeError
   277  }
   278  
   279  // AuthenticatorsFor gets the authenticators for the specified security schemes
   280  func (o *TaskTrackerAPI) AuthenticatorsFor(schemes map[string]spec.SecurityScheme) map[string]runtime.Authenticator {
   281  	result := make(map[string]runtime.Authenticator)
   282  	for name := range schemes {
   283  		switch name {
   284  		case "api_key":
   285  			scheme := schemes[name]
   286  			result[name] = o.APIKeyAuthenticator(scheme.Name, scheme.In, o.APIKeyAuth)
   287  
   288  		case "token_header":
   289  			scheme := schemes[name]
   290  			result[name] = o.APIKeyAuthenticator(scheme.Name, scheme.In, o.TokenHeaderAuth)
   291  
   292  		}
   293  	}
   294  	return result
   295  }
   296  
   297  // Authorizer returns the registered authorizer
   298  func (o *TaskTrackerAPI) Authorizer() runtime.Authorizer {
   299  	return o.APIAuthorizer
   300  }
   301  
   302  // ConsumersFor gets the consumers for the specified media types.
   303  // MIME type parameters are ignored here.
   304  func (o *TaskTrackerAPI) ConsumersFor(mediaTypes []string) map[string]runtime.Consumer {
   305  	result := make(map[string]runtime.Consumer, len(mediaTypes))
   306  	for _, mt := range mediaTypes {
   307  		switch mt {
   308  		case "application/vnd.goswagger.examples.task-tracker.v1+json":
   309  			result["application/vnd.goswagger.examples.task-tracker.v1+json"] = o.JSONConsumer
   310  		case "multipart/form-data":
   311  			result["multipart/form-data"] = o.MultipartformConsumer
   312  		}
   313  
   314  		if c, ok := o.customConsumers[mt]; ok {
   315  			result[mt] = c
   316  		}
   317  	}
   318  	return result
   319  }
   320  
   321  // ProducersFor gets the producers for the specified media types.
   322  // MIME type parameters are ignored here.
   323  func (o *TaskTrackerAPI) ProducersFor(mediaTypes []string) map[string]runtime.Producer {
   324  	result := make(map[string]runtime.Producer, len(mediaTypes))
   325  	for _, mt := range mediaTypes {
   326  		switch mt {
   327  		case "application/vnd.goswagger.examples.task-tracker.v1+json":
   328  			result["application/vnd.goswagger.examples.task-tracker.v1+json"] = o.JSONProducer
   329  		}
   330  
   331  		if p, ok := o.customProducers[mt]; ok {
   332  			result[mt] = p
   333  		}
   334  	}
   335  	return result
   336  }
   337  
   338  // HandlerFor gets a http.Handler for the provided operation method and path
   339  func (o *TaskTrackerAPI) HandlerFor(method, path string) (http.Handler, bool) {
   340  	if o.handlers == nil {
   341  		return nil, false
   342  	}
   343  	um := strings.ToUpper(method)
   344  	if _, ok := o.handlers[um]; !ok {
   345  		return nil, false
   346  	}
   347  	if path == "/" {
   348  		path = ""
   349  	}
   350  	h, ok := o.handlers[um][path]
   351  	return h, ok
   352  }
   353  
   354  // Context returns the middleware context for the task tracker API
   355  func (o *TaskTrackerAPI) Context() *middleware.Context {
   356  	if o.context == nil {
   357  		o.context = middleware.NewRoutableContext(o.spec, o, nil)
   358  	}
   359  
   360  	return o.context
   361  }
   362  
   363  func (o *TaskTrackerAPI) initHandlerCache() {
   364  	o.Context() // don't care about the result, just that the initialization happened
   365  	if o.handlers == nil {
   366  		o.handlers = make(map[string]map[string]http.Handler)
   367  	}
   368  
   369  	if o.handlers["POST"] == nil {
   370  		o.handlers["POST"] = make(map[string]http.Handler)
   371  	}
   372  	o.handlers["POST"]["/tasks/{id}/comments"] = tasks.NewAddCommentToTask(o.context, o.TasksAddCommentToTaskHandler)
   373  	if o.handlers["POST"] == nil {
   374  		o.handlers["POST"] = make(map[string]http.Handler)
   375  	}
   376  	o.handlers["POST"]["/tasks"] = tasks.NewCreateTask(o.context, o.TasksCreateTaskHandler)
   377  	if o.handlers["DELETE"] == nil {
   378  		o.handlers["DELETE"] = make(map[string]http.Handler)
   379  	}
   380  	o.handlers["DELETE"]["/tasks/{id}"] = tasks.NewDeleteTask(o.context, o.TasksDeleteTaskHandler)
   381  	if o.handlers["GET"] == nil {
   382  		o.handlers["GET"] = make(map[string]http.Handler)
   383  	}
   384  	o.handlers["GET"]["/tasks/{id}/comments"] = tasks.NewGetTaskComments(o.context, o.TasksGetTaskCommentsHandler)
   385  	if o.handlers["GET"] == nil {
   386  		o.handlers["GET"] = make(map[string]http.Handler)
   387  	}
   388  	o.handlers["GET"]["/tasks/{id}"] = tasks.NewGetTaskDetails(o.context, o.TasksGetTaskDetailsHandler)
   389  	if o.handlers["GET"] == nil {
   390  		o.handlers["GET"] = make(map[string]http.Handler)
   391  	}
   392  	o.handlers["GET"]["/tasks"] = tasks.NewListTasks(o.context, o.TasksListTasksHandler)
   393  	if o.handlers["PUT"] == nil {
   394  		o.handlers["PUT"] = make(map[string]http.Handler)
   395  	}
   396  	o.handlers["PUT"]["/tasks/{id}"] = tasks.NewUpdateTask(o.context, o.TasksUpdateTaskHandler)
   397  	if o.handlers["POST"] == nil {
   398  		o.handlers["POST"] = make(map[string]http.Handler)
   399  	}
   400  	o.handlers["POST"]["/tasks/{id}/files"] = tasks.NewUploadTaskFile(o.context, o.TasksUploadTaskFileHandler)
   401  }
   402  
   403  // Serve creates a http handler to serve the API over HTTP
   404  // can be used directly in http.ListenAndServe(":8000", api.Serve(nil))
   405  func (o *TaskTrackerAPI) Serve(builder middleware.Builder) http.Handler {
   406  	o.Init()
   407  
   408  	if o.Middleware != nil {
   409  		return o.Middleware(builder)
   410  	}
   411  	if o.useSwaggerUI {
   412  		return o.context.APIHandlerSwaggerUI(builder)
   413  	}
   414  	return o.context.APIHandler(builder)
   415  }
   416  
   417  // Init allows you to just initialize the handler cache, you can then recompose the middleware as you see fit
   418  func (o *TaskTrackerAPI) Init() {
   419  	if len(o.handlers) == 0 {
   420  		o.initHandlerCache()
   421  	}
   422  }
   423  
   424  // RegisterConsumer allows you to add (or override) a consumer for a media type.
   425  func (o *TaskTrackerAPI) RegisterConsumer(mediaType string, consumer runtime.Consumer) {
   426  	o.customConsumers[mediaType] = consumer
   427  }
   428  
   429  // RegisterProducer allows you to add (or override) a producer for a media type.
   430  func (o *TaskTrackerAPI) RegisterProducer(mediaType string, producer runtime.Producer) {
   431  	o.customProducers[mediaType] = producer
   432  }
   433  
   434  // AddMiddlewareFor adds a http middleware to existing handler
   435  func (o *TaskTrackerAPI) AddMiddlewareFor(method, path string, builder middleware.Builder) {
   436  	um := strings.ToUpper(method)
   437  	if path == "/" {
   438  		path = ""
   439  	}
   440  	o.Init()
   441  	if h, ok := o.handlers[um][path]; ok {
   442  		o.handlers[method][path] = builder(h)
   443  	}
   444  }