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