github.com/rzurga/go-swagger@v0.28.1-0.20211109195225-5d1f453ffa3a/examples/file-server/restapi/operations/file_upload_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/go-swagger/go-swagger/examples/file-server/restapi/operations/uploads"
    23  )
    24  
    25  // NewFileUploadAPI creates a new FileUpload instance
    26  func NewFileUploadAPI(spec *loads.Document) *FileUploadAPI {
    27  	return &FileUploadAPI{
    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  		UploadsUploadFileHandler: uploads.UploadFileHandlerFunc(func(params uploads.UploadFileParams) middleware.Responder {
    49  			return middleware.NotImplemented("operation uploads.UploadFile has not yet been implemented")
    50  		}),
    51  	}
    52  }
    53  
    54  /*FileUploadAPI Example server uploading a file */
    55  type FileUploadAPI struct {
    56  	spec            *loads.Document
    57  	context         *middleware.Context
    58  	handlers        map[string]map[string]http.Handler
    59  	formats         strfmt.Registry
    60  	customConsumers map[string]runtime.Consumer
    61  	customProducers map[string]runtime.Producer
    62  	defaultConsumes string
    63  	defaultProduces string
    64  	Middleware      func(middleware.Builder) http.Handler
    65  	useSwaggerUI    bool
    66  
    67  	// BasicAuthenticator generates a runtime.Authenticator from the supplied basic auth function.
    68  	// It has a default implementation in the security package, however you can replace it for your particular usage.
    69  	BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator
    70  
    71  	// APIKeyAuthenticator generates a runtime.Authenticator from the supplied token auth function.
    72  	// It has a default implementation in the security package, however you can replace it for your particular usage.
    73  	APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator
    74  
    75  	// BearerAuthenticator generates a runtime.Authenticator from the supplied bearer token auth function.
    76  	// It has a default implementation in the security package, however you can replace it for your particular usage.
    77  	BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator
    78  
    79  	// JSONConsumer registers a consumer for the following mime types:
    80  	//   - application/json
    81  	JSONConsumer runtime.Consumer
    82  	// MultipartformConsumer registers a consumer for the following mime types:
    83  	//   - multipart/form-data
    84  	MultipartformConsumer runtime.Consumer
    85  
    86  	// JSONProducer registers a producer for the following mime types:
    87  	//   - application/json
    88  	JSONProducer runtime.Producer
    89  
    90  	// UploadsUploadFileHandler sets the operation handler for the upload file operation
    91  	UploadsUploadFileHandler uploads.UploadFileHandler
    92  
    93  	// ServeError is called when an error is received, there is a default handler
    94  	// but you can set your own with this
    95  	ServeError func(http.ResponseWriter, *http.Request, error)
    96  
    97  	// PreServerShutdown is called before the HTTP(S) server is shutdown
    98  	// This allows for custom functions to get executed before the HTTP(S) server stops accepting traffic
    99  	PreServerShutdown func()
   100  
   101  	// ServerShutdown is called when the HTTP(S) server is shut down and done
   102  	// handling all active connections and does not accept connections any more
   103  	ServerShutdown func()
   104  
   105  	// Custom command line argument groups with their descriptions
   106  	CommandLineOptionsGroups []swag.CommandLineOptionsGroup
   107  
   108  	// User defined logger function.
   109  	Logger func(string, ...interface{})
   110  }
   111  
   112  // UseRedoc for documentation at /docs
   113  func (o *FileUploadAPI) UseRedoc() {
   114  	o.useSwaggerUI = false
   115  }
   116  
   117  // UseSwaggerUI for documentation at /docs
   118  func (o *FileUploadAPI) UseSwaggerUI() {
   119  	o.useSwaggerUI = true
   120  }
   121  
   122  // SetDefaultProduces sets the default produces media type
   123  func (o *FileUploadAPI) SetDefaultProduces(mediaType string) {
   124  	o.defaultProduces = mediaType
   125  }
   126  
   127  // SetDefaultConsumes returns the default consumes media type
   128  func (o *FileUploadAPI) SetDefaultConsumes(mediaType string) {
   129  	o.defaultConsumes = mediaType
   130  }
   131  
   132  // SetSpec sets a spec that will be served for the clients.
   133  func (o *FileUploadAPI) SetSpec(spec *loads.Document) {
   134  	o.spec = spec
   135  }
   136  
   137  // DefaultProduces returns the default produces media type
   138  func (o *FileUploadAPI) DefaultProduces() string {
   139  	return o.defaultProduces
   140  }
   141  
   142  // DefaultConsumes returns the default consumes media type
   143  func (o *FileUploadAPI) DefaultConsumes() string {
   144  	return o.defaultConsumes
   145  }
   146  
   147  // Formats returns the registered string formats
   148  func (o *FileUploadAPI) Formats() strfmt.Registry {
   149  	return o.formats
   150  }
   151  
   152  // RegisterFormat registers a custom format validator
   153  func (o *FileUploadAPI) RegisterFormat(name string, format strfmt.Format, validator strfmt.Validator) {
   154  	o.formats.Add(name, format, validator)
   155  }
   156  
   157  // Validate validates the registrations in the FileUploadAPI
   158  func (o *FileUploadAPI) Validate() error {
   159  	var unregistered []string
   160  
   161  	if o.JSONConsumer == nil {
   162  		unregistered = append(unregistered, "JSONConsumer")
   163  	}
   164  	if o.MultipartformConsumer == nil {
   165  		unregistered = append(unregistered, "MultipartformConsumer")
   166  	}
   167  
   168  	if o.JSONProducer == nil {
   169  		unregistered = append(unregistered, "JSONProducer")
   170  	}
   171  
   172  	if o.UploadsUploadFileHandler == nil {
   173  		unregistered = append(unregistered, "uploads.UploadFileHandler")
   174  	}
   175  
   176  	if len(unregistered) > 0 {
   177  		return fmt.Errorf("missing registration: %s", strings.Join(unregistered, ", "))
   178  	}
   179  
   180  	return nil
   181  }
   182  
   183  // ServeErrorFor gets a error handler for a given operation id
   184  func (o *FileUploadAPI) ServeErrorFor(operationID string) func(http.ResponseWriter, *http.Request, error) {
   185  	return o.ServeError
   186  }
   187  
   188  // AuthenticatorsFor gets the authenticators for the specified security schemes
   189  func (o *FileUploadAPI) AuthenticatorsFor(schemes map[string]spec.SecurityScheme) map[string]runtime.Authenticator {
   190  	return nil
   191  }
   192  
   193  // Authorizer returns the registered authorizer
   194  func (o *FileUploadAPI) Authorizer() runtime.Authorizer {
   195  	return nil
   196  }
   197  
   198  // ConsumersFor gets the consumers for the specified media types.
   199  // MIME type parameters are ignored here.
   200  func (o *FileUploadAPI) ConsumersFor(mediaTypes []string) map[string]runtime.Consumer {
   201  	result := make(map[string]runtime.Consumer, len(mediaTypes))
   202  	for _, mt := range mediaTypes {
   203  		switch mt {
   204  		case "application/json":
   205  			result["application/json"] = o.JSONConsumer
   206  		case "multipart/form-data":
   207  			result["multipart/form-data"] = o.MultipartformConsumer
   208  		}
   209  
   210  		if c, ok := o.customConsumers[mt]; ok {
   211  			result[mt] = c
   212  		}
   213  	}
   214  	return result
   215  }
   216  
   217  // ProducersFor gets the producers for the specified media types.
   218  // MIME type parameters are ignored here.
   219  func (o *FileUploadAPI) ProducersFor(mediaTypes []string) map[string]runtime.Producer {
   220  	result := make(map[string]runtime.Producer, len(mediaTypes))
   221  	for _, mt := range mediaTypes {
   222  		switch mt {
   223  		case "application/json":
   224  			result["application/json"] = o.JSONProducer
   225  		}
   226  
   227  		if p, ok := o.customProducers[mt]; ok {
   228  			result[mt] = p
   229  		}
   230  	}
   231  	return result
   232  }
   233  
   234  // HandlerFor gets a http.Handler for the provided operation method and path
   235  func (o *FileUploadAPI) HandlerFor(method, path string) (http.Handler, bool) {
   236  	if o.handlers == nil {
   237  		return nil, false
   238  	}
   239  	um := strings.ToUpper(method)
   240  	if _, ok := o.handlers[um]; !ok {
   241  		return nil, false
   242  	}
   243  	if path == "/" {
   244  		path = ""
   245  	}
   246  	h, ok := o.handlers[um][path]
   247  	return h, ok
   248  }
   249  
   250  // Context returns the middleware context for the file upload API
   251  func (o *FileUploadAPI) Context() *middleware.Context {
   252  	if o.context == nil {
   253  		o.context = middleware.NewRoutableContext(o.spec, o, nil)
   254  	}
   255  
   256  	return o.context
   257  }
   258  
   259  func (o *FileUploadAPI) initHandlerCache() {
   260  	o.Context() // don't care about the result, just that the initialization happened
   261  	if o.handlers == nil {
   262  		o.handlers = make(map[string]map[string]http.Handler)
   263  	}
   264  
   265  	if o.handlers["POST"] == nil {
   266  		o.handlers["POST"] = make(map[string]http.Handler)
   267  	}
   268  	o.handlers["POST"]["/upload"] = uploads.NewUploadFile(o.context, o.UploadsUploadFileHandler)
   269  }
   270  
   271  // Serve creates a http handler to serve the API over HTTP
   272  // can be used directly in http.ListenAndServe(":8000", api.Serve(nil))
   273  func (o *FileUploadAPI) Serve(builder middleware.Builder) http.Handler {
   274  	o.Init()
   275  
   276  	if o.Middleware != nil {
   277  		return o.Middleware(builder)
   278  	}
   279  	if o.useSwaggerUI {
   280  		return o.context.APIHandlerSwaggerUI(builder)
   281  	}
   282  	return o.context.APIHandler(builder)
   283  }
   284  
   285  // Init allows you to just initialize the handler cache, you can then recompose the middleware as you see fit
   286  func (o *FileUploadAPI) Init() {
   287  	if len(o.handlers) == 0 {
   288  		o.initHandlerCache()
   289  	}
   290  }
   291  
   292  // RegisterConsumer allows you to add (or override) a consumer for a media type.
   293  func (o *FileUploadAPI) RegisterConsumer(mediaType string, consumer runtime.Consumer) {
   294  	o.customConsumers[mediaType] = consumer
   295  }
   296  
   297  // RegisterProducer allows you to add (or override) a producer for a media type.
   298  func (o *FileUploadAPI) RegisterProducer(mediaType string, producer runtime.Producer) {
   299  	o.customProducers[mediaType] = producer
   300  }
   301  
   302  // AddMiddlewareFor adds a http middleware to existing handler
   303  func (o *FileUploadAPI) AddMiddlewareFor(method, path string, builder middleware.Builder) {
   304  	um := strings.ToUpper(method)
   305  	if path == "/" {
   306  		path = ""
   307  	}
   308  	o.Init()
   309  	if h, ok := o.handlers[um][path]; ok {
   310  		o.handlers[method][path] = builder(h)
   311  	}
   312  }