rest

package module
v0.8.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 19, 2020 License: MIT Imports: 11 Imported by: 0

README

rest

Rest is an experimental web resource abstraction for composing REST APIs in Go (Golang).

  • Rapid prototyping.
  • Web Server generation (http.Handler)
  • REST API Specification generation (OpenAPI v2)

Base components:

  • API: It's the root that contains resources and server information. Also, it generates the server handler and the API specification.
  • Resource: Each resource is a node in a URL path, and contains methods and other resources.

Code example:

api := rest.NewAPI("/api/v1", "localhost", "My simple car API", "v1")

api.Resource("car", func(r *rest.Resource) {
	r.Resource("findMatch", func(r *rest.Resource) {
	})
	carID := rest.NewURIParameter("carID", reflect.String)
	r.ResourceP(carID, func(r *rest.Resource) {
	})
})

api.Resource("ping", func(r *rest.Resource) {
})

api.Resource("user", func(r *rest.Resource) {
	r.Resource("signOut", func(r *rest.Resource) {
	})
})
	

Diagram of the above code:

                                     +-----------+
                                     |   API     |
                          +----------+   "/2"    +-----------+
                          |          |           |           |
                          |          +-----+-----+           |
                          |                |                 |
                   +------v-----+    +-----v------+    +-----v------+
                   |  Resource  |    |  Resource  |    |  Resource  |
       +-----------+   "car"    |    |   "ping"   |    |  "user"    |
       |           |            |    |            |    |            |
       |           +-----+------+    +------------+    +-----+------+
       |                 |                                   |
+------v-----+     +-----v------+                      +-----v------+
|  Resource  |     |  Resource  |                      |  Resource  |
| "findMatch"|     | "{carId}"  |                      |  "signOut" |
|            |     |            |                      |            |
+------------+     +------------+                      +------------+

API methods:

  • GenerateServer(g rest.ServerGenerator) http.Handler
  • GenerateSpec(w io.Writer, api rest.API)

Example:

api := rest.NewAPI("/v1", "localhost", "My simple car API", "v1")
// Generating OpenAPI v2 specification to standard output
api.GenerateSpec(os.Stdout, &oaiv2.OpenAPIV2SpecGenerator{})
// Generating server handler
server := api.GenerateServer(chigenerator.ChiGenerator{})

Resource

Resource main components:

  • Methods: A collection of HTTP methods.
  • Resources: Collection of child resources.

Example:

api.Resource("user", func(r *rest.Resource) {
    // Method
    r.Get(getUser, ct)
    // Resource
    r.Resource("logout", func(r *rest.Resource) {
        // Method
        r.Get(logOut, ct)
    })
})

ResourceP (URI parameter Resource)

ResourceP creates a new URI parameter resource node. The first argument must be a Parameter of URIParameter type. Use NewURIParameter to create one.

Example:

carID := rest.NewURIParameter("carID", reflect.String)
r.ResourceP(carID, func(r *rest.Resource) {
    r.Get(getCar, ct).WithParameter(carID)
})

In the example the route to get a car will be /car/{carID}, where {carID} is the variable part.

Method

A Method represents an HTTP method with an HTTP Handler. A default handler will make sense of the method specification and return the appropriate HTTP response. The specification elements to be managed by the default handler are: Content negotiation, security, validation, and operation.

  • MethodOperation: Describes an Operation and responses (Response for success and failure).
  • ContentTypes: Describes the available content-types and encoder/decoders for request and responses.
  • Negotiator: Interface for content negotiation. A default implementation will be set when you create a Method.
  • SecurityCollection: Is the security definition.
  • Parameters: The parameters expected to be sent by the client. The main purpose of the declaration of parameters is for API specification generation.
  • Handler: The http.Handler of the method. The default handler will be set when you create a new Method.
Operation

Represents a logical operation upon a resource, like delete, list, create, ping, etc. Operation is an interface defined by an Execute method.

Execute method
  • Inputs: Input type

  • Output: body interface{}, success bool, and err error .

    1. body (interface{}): Is the body that is going to be send to the client.(Optional)
    2. success (bool): If the value is true, it will trigger the successResponse (argument passed in the NewMethodOperation function). If the value is false, it will trigger the failResponse (set it with WithFailResponse method). False means that the most positive operation output didn't happened, but is not an API nor a client error.
    3. err (error): The err(error) is meant to indicate an API error, or any internal server error, like a database failure, i/o error, etc. The err!=nil will always trigger a 500 code error.
Method:
                               +----------------+
                               |                |
                               |     Method     |
                               |                |
                               +--------+-------+
                                        |
                               +--------+-------+
                               |                |
                           +---+ MethodOperation+---+
                           |   |                |   |
Your operation method      |   +--------+-------+   |
goes here                  |            |           |
      +                    |            |           |
      |             +------+----+ +-----+-----+ +---+-------+
      |             |           | | Response  | |  Response |
      +-----------> | Operation | | success   | |  fail     |
                    |           | |           | |           |
                    +-----------+ +-----------+ +-----------+

Full code example:

// Responses
successResponse := rest.NewResponse(200).WithOperationResultBody(Car{})
failResponse := rest.NewResponse(404)

getCarOperation := func(i rest.Input) (body interface{}, success bool, err error) {
    carID, err := i.GetURIParam("carID")

    if err != nil {
        log.Println("error getting parameter: ", err)
        return Car{}, false, err
    }

    if carID == "error" {
        // Internal error trying to get the car. This will trigger a response code 500
        return nil, false, errors.New("Internal error")
    }

    if carID != "101" {
        // Car not found, success is false, no error. This will trigger the `failResponse` (response code 404)
        return nil, false, nil
    }

    // Car found, success true, error nil. This will trigger the `successResponse` (response code 200)
    return Car{carID, "Foo"}, true, nil
}
// Method Operation
getCar := rest.NewMethodOperation(rest.OperationFunc(getCarOperation), successResponse).WithFailResponse(failResponse)
// ContentTypes
ct := rest.NewContentTypes()
ct.Add("application/json", encdec.JSONEncoderDecoder{}, true)

api := rest.NewAPI("/v1", "localhost", "My simple car API", "v1")
api.Resource("car", func(r *rest.Resource) {
    carID := rest.NewURIParameter("carID", reflect.String)
    r.ResourceP(carID, func(r *rest.Resource) {
        r.Get(getCar, ct).WithParameter(carID)
    })
})
// Generating OpenAPI v2 specification to standard output
api.GenerateSpec(os.Stdout, &oaiv2.OpenAPIV2SpecGenerator{})

// Generating server routes
server := api.GenerateServer(chigenerator.ChiGenerator{})
http.ListenAndServe(":8080", server)

Documentation

Index

Constants

View Source
const (
	// URIReservedChar is the reserved char set as in RFC 3986 (https://tools.ietf.org/html/rfc3986#section-2.2)
	URIReservedChar = ":/?#[]@!$&'()*+,;="
	// ResourceReservedChar is URIReservedChar + "{}" that represents the charset that is not allowed on resource names.
	// The curly brackets are reserved for internally denoting a path URI parameter, also used by API specification formats.
	ResourceReservedChar = URIReservedChar + "{}"
)
View Source
const (
	// BasicSecurityType is the basic authentication security scheme
	BasicSecurityType = "basic"
	// APIKeySecurityType is the API Key authentication security scheme
	APIKeySecurityType = "apiKey"
	// OAuth2SecurityType is the OAuth2 authentication security scheme
	OAuth2SecurityType = "oauth2"
)
View Source
const (
	// FlowAuthCodeType is the `authorization` code flow or grant type in a OAuth2 security scheme
	FlowAuthCodeType = "authorization_code"
	// FlowPasswordType is the `password` flow or grant type in a OAuth2 security scheme
	FlowPasswordType = "password"
	// FlowClientCredentialType is the `client credentials` flow or grant type in a OAuth2 security scheme
	FlowClientCredentialType = "client_credentials"
	// FlowImplicitType is the `implicit` flow or grant type in a OAuth2 security scheme
	FlowImplicitType = "implicit"
)

Variables

View Source
var ErrorNoDefaultContentTypeIsSet = errors.New("rest: no default content-type is set")

ErrorNoDefaultContentTypeIsSet error when no default content-type is set

View Source
var ErrorRequestBodyNotDefined = errors.New("rest: a request body was not defined")

ErrorRequestBodyNotDefined error describes a specification/parameter check error trying to get the request body, but it was not declared as parameter.

Functions

This section is empty.

Types

type API

type API struct {
	ID          string
	Version     string
	Description string
	Title       string
	Host        string
	BasePath    string
	ResourceCollection
}

API is the root of a REST API abstraction. The two main responsibilities are specification generation (GenerateSpec function), and Server handler generation (GenerateServer function).

func NewAPI

func NewAPI(basePath, hostname, title, version string) API

NewAPI creates a new API.

func (API) GenerateServer

func (a API) GenerateServer(g ServerGenerator) http.Handler

GenerateServer generates a http.Handler using a ServerGenerator implementation (g)

func (API) GenerateSpec

func (a API) GenerateSpec(w io.Writer, g APISpecGenerator)

GenerateSpec will generate the API specification using APISpecGenerator interface implementation (g), and will write into a io.Writer implementation (w)

type APISpecGenerator

type APISpecGenerator interface {
	GenerateAPISpec(w io.Writer, api API)
}

APISpecGenerator is the interface implemented by types that transform a API type into an REST API specification, in a specific format and writing it to w.

type AuthError

type AuthError interface {
	Error() string
	// contains filtered or unexported methods
}

AuthError describes an authentication/authorization error. Use the following implementations: For an authentication failure use the TypeErrorAuthentication error. For an authorization failure use TypeErrorAuthorization error

type Authenticator

type Authenticator interface {
	Authenticate(Input) AuthError
}

Authenticator describes the method for authentication/authorization. AuthError represents either an authentication or authorization failure. Authentication function should be executed first, then the authorization. To indicate an authentication failure return a TypeErrorAuthentication, and for an authorization failure TypeErrorAuthorization error type. AuthError will be nil when both authentication and authorization are successful

type AuthenticatorFunc

type AuthenticatorFunc func(Input) AuthError

The AuthenticatorFunc type is an adapter to allow the use of ordinary functions as Authenticator. If f is a function with the appropriate signature, AuthenticatorFunc(f) is a Authenticator that calls f.

func (AuthenticatorFunc) Authenticate

func (f AuthenticatorFunc) Authenticate(i Input) AuthError

Authenticate calls f(i)

type CollectionParam

type CollectionParam struct {
	CollectionFormat string
	EnumValues       []interface{}
}

CollectionParam is a subset of properties for array type query parameters

type ContentTypeContextKey

type ContentTypeContextKey string

ContentTypeContextKey is the type used to pass the mime-types values through the Context of the request. The values are set by the Negotiator implementation.

type ContentTypes added in v0.2.0

type ContentTypes struct {
	UnsupportedMediaTypeResponse Response
	// contains filtered or unexported fields
}

ContentTypes contains all available MIME types, associated with their respective Encoder/Decoder.

func NewContentTypes added in v0.2.0

func NewContentTypes() ContentTypes

NewContentTypes will create a new ContentTypes instance

func (*ContentTypes) Add added in v0.2.0

func (h *ContentTypes) Add(mimeType string, ed encdec.EncoderDecoder, isDefault bool)

Add adds a EncoderDecoder. isDefault parameter will set the default encoder and decoder.

func (*ContentTypes) AddDecoder added in v0.2.0

func (h *ContentTypes) AddDecoder(mimeType string, decoder encdec.Decoder, isDefault bool)

AddDecoder adds a decoder. isDefault parameter will set this decoder as default.

func (*ContentTypes) AddEncoder added in v0.2.0

func (h *ContentTypes) AddEncoder(mimeType string, encoder encdec.Encoder, isDefault bool)

AddEncoder adds a encoder. isDefault parameter sets this encoder as default.

func (*ContentTypes) GetDecoder added in v0.2.0

func (h *ContentTypes) GetDecoder(mimeType string) (encdec.Decoder, error)

GetDecoder gets the decoder with the provided mimeType as key

func (*ContentTypes) GetDefaultDecoder added in v0.2.0

func (h *ContentTypes) GetDefaultDecoder() (string, encdec.Decoder, error)

GetDefaultDecoder gets the default decoder.

func (*ContentTypes) GetDefaultEncoder added in v0.2.0

func (h *ContentTypes) GetDefaultEncoder() (string, encdec.Encoder, error)

GetDefaultEncoder gets default encoder.

func (*ContentTypes) GetEncoder added in v0.2.0

func (h *ContentTypes) GetEncoder(mimeType string) (encdec.Encoder, error)

GetEncoder gets the encoder with the provided mimeType as key

type DefaultNegotiator

type DefaultNegotiator struct {
}

DefaultNegotiator is an implementation of a Negotiator

func (DefaultNegotiator) NegotiateDecoder

func (d DefaultNegotiator) NegotiateDecoder(r *http.Request, cts *ContentTypes) (string, encdec.Decoder, error)

NegotiateDecoder resolves the MIME type and Decoder to be used by the Handler to process the request.

func (DefaultNegotiator) NegotiateEncoder

func (d DefaultNegotiator) NegotiateEncoder(r *http.Request, cts *ContentTypes) (string, encdec.Encoder, error)

NegotiateEncoder resolves the MIME type and Encoder to be used by the Handler to process the response.

type EncoderDecoderContextKey

type EncoderDecoderContextKey string

EncoderDecoderContextKey is the type used to pass the Encoder/Decoder values the Context of the request. The values are set by the Negotiator implementation.

type ErrorAuthentication added in v0.8.0

type ErrorAuthentication struct {
	Message string
}

ErrorAuthentication is an AuthError implementation respresenting an authentication failure

func (ErrorAuthentication) Error added in v0.8.0

func (ia ErrorAuthentication) Error() string

type ErrorAuthorization added in v0.8.0

type ErrorAuthorization struct {
	Message string
}

ErrorAuthorization is an AuthError implementation respresenting an authorization failure

func (ErrorAuthorization) Error added in v0.8.0

func (ia ErrorAuthorization) Error() string

type ErrorFailResponseNotDefined added in v0.8.0

type ErrorFailResponseNotDefined struct {
	Name string
}

ErrorFailResponseNotDefined will be trigger when the fail response in the Operation was not defined, but the Execute method returns a false value in the success return value.

func (*ErrorFailResponseNotDefined) Error added in v0.8.0

type ErrorGetURIParamFunctionNotDefined added in v0.8.0

type ErrorGetURIParamFunctionNotDefined struct {
	Name string
}

ErrorGetURIParamFunctionNotDefined describes a problem when the method GetURIParam has not been declared or correctely set up in the context value key by the ServerGenerator implementation.

func (*ErrorGetURIParamFunctionNotDefined) Error added in v0.8.0

type ErrorParameterCharNotAllowed added in v0.8.0

type ErrorParameterCharNotAllowed struct {
	Name string
}

ErrorParameterCharNotAllowed error when a forbidden character is included in the `name` parameter of a `Parameter`.

func (*ErrorParameterCharNotAllowed) Error added in v0.8.0

type ErrorParameterNotDefined added in v0.8.0

type ErrorParameterNotDefined struct {
	Name string
}

ErrorParameterNotDefined describes a specification/parameter check error trying to get a parameter, but it was not declared.

func (*ErrorParameterNotDefined) Error added in v0.8.0

func (e *ErrorParameterNotDefined) Error() string

type ErrorResourceCharNotAllowed added in v0.8.0

type ErrorResourceCharNotAllowed struct {
	Name string
}

ErrorResourceCharNotAllowed error when a forbidden character is included in the `name` parameter of a `Resource`.

func (*ErrorResourceCharNotAllowed) Error added in v0.8.0

type Input

type Input struct {
	Request              *http.Request
	Parameters           ParameterCollection
	RequestBodyParameter RequestBody
	BodyDecoder          encdec.Decoder
}

Input type is the main parameter of the Execute method of an Operation interface implementation. Input getter methods are intended to be used as a specification-implementation check control, so if a parameter was not defined will return an error. Request property provide access to the http.Request pointer. Parameters is the collection of parameter defined for the method. RequestBodyParameter parameter is the Request Body defined for the method.

func (Input) GetBody

func (i Input) GetBody() (io.ReadCloser, error)

GetBody gets the request body, error if is not defined.

func (Input) GetFormFile

func (i Input) GetFormFile(key string) ([]byte, *multipart.FileHeader, error)

GetFormFile gets the first file content and header for the provided form key. If the parameter is not defined, will return error.

func (Input) GetFormFiles

func (i Input) GetFormFiles(key string) ([]*multipart.FileHeader, error)

GetFormFiles gets all the files of a multipart form with the provided key, in a slice of *multipart.FileHeader If the parameter is not defined will return error, as well any other error will be returned if a problem is find getting the files.

func (Input) GetFormValue

func (i Input) GetFormValue(key string) (string, error)

GetFormValue gets the first value for the named component of the query. FormValue calls FormValue from the standard library. If the parameter is not defined, will return error.

func (Input) GetFormValues

func (i Input) GetFormValues(key string) ([]string, error)

GetFormValues gets the values associated with the provided key. If the parameter is not defined will return error. Will also return an error if any error is found getting the values.

func (Input) GetHeader

func (i Input) GetHeader(key string) (string, error)

GetHeader gets the request query slice associated to the given key. If the parameter is not defined it will return an error.

func (Input) GetQuery

func (i Input) GetQuery(key string) ([]string, error)

GetQuery gets the request query slice associated to the given key. If the parameter is not defined, will return an error.

func (Input) GetQueryString

func (i Input) GetQueryString(key string) (string, error)

GetQueryString gets the first value associated with the given key. If there are no values associated with the key, GetQueryString returns the empty string. If the parameter is not defined, will return error. To access multiple values, use GetQuery

func (Input) GetURIParam

func (i Input) GetURIParam(key string) (string, error)

GetURIParam gets the URI Param using the InputContextKey("uriparamfunc") context value. If the InputContextKey("uriparamfunc") context value is not set will return an error. If the URI parameter is not set, will return an error.

type InputContextKey

type InputContextKey string

InputContextKey is the type used to pass the URI Parameter function through the Context of the request. The values are set by the GenerateServer method of the API type.

type Method

type Method struct {
	HTTPMethod      string
	Summary         string
	Description     string
	RequestBody     RequestBody
	MethodOperation MethodOperation

	Negotiator
	SecurityCollection []Security
	http.Handler
	ParameterCollection
	// contains filtered or unexported fields
}

Method represents a http operation that is performed on a resource.

func NewMethod

func NewMethod(httpMethod string, methodOperation MethodOperation, contentTypes ContentTypes) *Method

NewMethod returns a Method instance

func (*Method) GetDecoderMediaTypes

func (m *Method) GetDecoderMediaTypes() []string

GetDecoderMediaTypes gets a string slice of the method's decoder media types

func (*Method) GetEncoderMediaTypes

func (m *Method) GetEncoderMediaTypes() []string

GetEncoderMediaTypes gets a string slice of the method's encoder media types

func (*Method) OverwriteCoreSecurityMiddleware added in v0.5.0

func (m *Method) OverwriteCoreSecurityMiddleware(mid Middleware) *Method

OverwriteSecurityMiddleware replaces the core security middleware with the provided middleware for this method.

func (*Method) Responses

func (m *Method) Responses() []Response

Responses gets the response collection of the method.

func (*Method) WithDescription

func (m *Method) WithDescription(description string) *Method

WithDescription sets the description property

func (*Method) WithParameter

func (m *Method) WithParameter(parameter Parameter) *Method

WithParameter will add a new parameter to the collection with the unique key composed by the HTTPType and Name properties. It will silently override a parameter with the same key.

func (*Method) WithRequestBody

func (m *Method) WithRequestBody(description string, body interface{}) *Method

WithRequestBody sets the RequestBody property

func (*Method) WithSecurity

func (m *Method) WithSecurity(s ...*SecurityScheme) *Method

Security adds a set of one or more security schemes. When more than one Security is defined it will follow an `or` logic with other Security definitions.

func (*Method) WithSummary

func (m *Method) WithSummary(summary string) *Method

WithSummary sets the summary property

func (*Method) WithValidation

func (m *Method) WithValidation(v Validation) *Method

WithValidation sets the validation operation and the response in case of validation error.

type MethodOperation

type MethodOperation struct {
	// Logic operation of the method
	Operation
	// contains filtered or unexported fields
}

MethodOperation contains the operation, and its responses for success and failure. Operation Execute method will return a body (interface{}), success (bool), and err (error).

func NewMethodOperation

func NewMethodOperation(operation Operation, successResponse Response) MethodOperation

NewMethodOperation returns a new MethodOperation instance. successResponse: This response will be returned if the operation success return value is true, and the error value is nil. failedResponse: This response will be returned if the operation success value is false. Please check if your operation returns a success false, if you don't define a failure response, and your operation returns a success false, the HTTP Server could return a panic.

func (MethodOperation) WithFailResponse

func (m MethodOperation) WithFailResponse(failResponse Response) MethodOperation

WithFailResponse sets the failResponse property

type Middleware added in v0.4.0

type Middleware func(http.Handler) http.Handler

Middleware is a function that gets a `next` Handler and returns the middleware Handler

type MutableResponseBody

type MutableResponseBody interface {
	Mutate(operationResultBody interface{}, success bool, err error)
}

MutableResponseBody is an interface that represents the Http body response that can mutate after a validation or an operation, taking the outputs of this methods as inputs.

type Negotiator

type Negotiator interface {
	NegotiateEncoder(*http.Request, *ContentTypes) (MIMEType string, encoder encdec.Encoder, err error)
	NegotiateDecoder(*http.Request, *ContentTypes) (MIMEType string, decoder encdec.Decoder, err error)
}

Negotiator interface describe the necessary methods to process the HTTP content negotiation logic.

type OAuth2Flow

type OAuth2Flow struct {
	Name             string
	AuthorizationURL string
	TokenURL         string
	RefreshURL       string
	Scopes           map[string]string
}

OAuth2Flow contains the OAuth2 flow or grant information.

type Operation

type Operation interface {
	Execute(i Input) (body interface{}, success bool, err error)
}

Operation defines a resource operation. Execute method will execute the operation. Return values: `body`: can be nil, and it will be the body to be returned if the operation's success response is set with `WithOperationResultBody`. `success`: should be true if the operation got the most positive outcome. Success with false value means that the operation has no errors, but the positive outcome was not achieved (something was not found in a database). `err`: means that an error was risen and the operation was not executed because an internal error in the API. Error should cause a 500's http error code.

type OperationFunc

type OperationFunc func(i Input) (body interface{}, success bool, err error)

The OperationFunc type is an adapter to allow the use of ordinary functions as Operation. If f is a function with the appropriate signature, OperationFunc(f) is a Operation that calls f.

func (OperationFunc) Execute

func (f OperationFunc) Execute(i Input) (body interface{}, success bool, err error)

Execute calls f(i)

type Parameter

type Parameter struct {
	Description string
	Name        string
	HTTPType    ParameterType
	Type        reflect.Kind
	Body        interface{}
	Decoder     encdec.Decoder
	Required    bool
	CollectionParam

	Example interface{}
	// contains filtered or unexported fields
}

Parameter unique key is defined by a combination of a HTTPType and Name property

func NewFileParameter

func NewFileParameter(name string) Parameter

NewFileParameter creates a FileParameter Parameter. Required property is false by default

func NewFormDataParameter

func NewFormDataParameter(name string, tpe reflect.Kind, decoder encdec.Decoder) Parameter

NewFormDataParameter creates a FormDataParameter Parameter. Required property is false by default

func NewHeaderParameter

func NewHeaderParameter(name string, tpe reflect.Kind) Parameter

NewHeaderParameter creates a HeaderParameter Parameter. Required property is false by default

func NewQueryArrayParameter

func NewQueryArrayParameter(name string, enumValues []interface{}) Parameter

NewQueryArrayParameter creates a QueryParameter Parameter. Required property is false by default

func NewQueryParameter

func NewQueryParameter(name string, tpe reflect.Kind) Parameter

NewQueryParameter creates a QueryParameter Parameter. Required property is false by default

func NewURIParameter

func NewURIParameter(name string, tpe reflect.Kind) Parameter

NewURIParameter creates a URIParameter Parameter. Required property is true by default

func (Parameter) AsOptional

func (p Parameter) AsOptional() Parameter

AsOptional sets the Required property to false

func (Parameter) AsRequired

func (p Parameter) AsRequired() Parameter

AsRequired sets the Required property to true

func (Parameter) WithBody

func (p Parameter) WithBody(body interface{}) Parameter

WithBody sets the body property

func (Parameter) WithDescription

func (p Parameter) WithDescription(description string) Parameter

WithDescription sets the description property

func (Parameter) WithExample

func (p Parameter) WithExample(example interface{}) Parameter

WithExample sets the example property

func (Parameter) WithValidation

func (p Parameter) WithValidation(v Validation) Parameter

WithValidation sets the validation property

type ParameterCollection

type ParameterCollection struct {
	// contains filtered or unexported fields
}

ParameterCollection is a collection of parameters

func NewParameterCollection

func NewParameterCollection() ParameterCollection

NewParameterCollection returns a new ParameterCollection

func (*ParameterCollection) AddParameter

func (p *ParameterCollection) AddParameter(parameter Parameter)

AddParameter adds a new parameter to the collection with the unique composite key by HTTPType and Name properties. It will silently override a parameter if the same key is already set.

func (*ParameterCollection) GetParameter

func (p *ParameterCollection) GetParameter(paramType ParameterType, name string) (Parameter, error)

GetParameter gets the parameter of the given ParameterType and name, error if is not found.

func (*ParameterCollection) Parameters

func (p *ParameterCollection) Parameters() []Parameter

Parameters gets the parameter collection. The order of the slice elements will not be consistent.

type ParameterType

type ParameterType string

ParameterType represents a HTTP parameter type

const (
	FormDataParameter ParameterType = "formData"
	FileParameter     ParameterType = "file"
	HeaderParameter   ParameterType = "header"
	QueryParameter    ParameterType = "query"
	URIParameter      ParameterType = "uri"
)

Common HTTP parameter types

type RequestBody

type RequestBody struct {
	Description string
	Body        interface{}
	Required    bool
}

RequestBody represents a request body parameter

type Resource

type Resource struct {
	Summary     string
	Description string

	ResourceCollection
	// contains filtered or unexported fields
}

Resource represents a REST API resource, and a node in a URL tree path. It contains a collection of resource methods, and a collection of resources.

func NewResource

func NewResource(name string) Resource

NewResource creates a new resource node. `name` parameter value should not contain any reserved chars like ":/?#[]@!$&'()*+,;=" (RFC 3986 https://tools.ietf.org/html/rfc3986#section-2.2) nor curly brackets "{}"

func NewResourceP added in v0.7.0

func NewResourceP(p Parameter) Resource

NewResourceP creates a new URI parameter resource node. p Parameter must be URIParameter type. Use NewURIParameter to create one.

func (*Resource) AddMethod

func (rs *Resource) AddMethod(method *Method)

AddMethod adds a new method to the method collection. If the same HTTPMethod (POST, GET, etc) is already in the collection, will be replaced silently. The current resource's middleware stack will be applied

func (*Resource) Connect

func (rs *Resource) Connect(methodOperation MethodOperation, ct ContentTypes) *Method

Connect adds a new CONNECT method to the method collection

func (*Resource) Delete

func (rs *Resource) Delete(methodOperation MethodOperation, ct ContentTypes) *Method

Delete adds a new DELETE method to the method collection

func (*Resource) Get

func (rs *Resource) Get(methodOperation MethodOperation, ct ContentTypes) *Method

Get adds a new GET method to the method collection

func (*Resource) Head

func (rs *Resource) Head(methodOperation MethodOperation, ct ContentTypes) *Method

Head adds a new HEAD method to the method collection

func (*Resource) Methods

func (rs *Resource) Methods() []Method

Methods returns the method collection

func (*Resource) Options

func (rs *Resource) Options(methodOperation MethodOperation, ct ContentTypes) *Method

Options adds a new OPTIONS method to the method collection

func (*Resource) OverwriteCoreSecurityMiddleware added in v0.5.0

func (rs *Resource) OverwriteCoreSecurityMiddleware(m Middleware)

OverwriteCoreSecurityMiddleware will replace the core default security middleware of all the child methods and resources declared after the call of this method.

func (*Resource) Patch

func (rs *Resource) Patch(methodOperation MethodOperation, ct ContentTypes) *Method

Patch adds a new PATCH method to the method collection

func (*Resource) Path

func (rs *Resource) Path() string

Path returns the name and path property.

func (*Resource) Post

func (rs *Resource) Post(methodOperation MethodOperation, ct ContentTypes) *Method

Post adds a new POST method to the method collection

func (*Resource) Put

func (rs *Resource) Put(methodOperation MethodOperation, ct ContentTypes) *Method

Put adds a new PUT method to the method collection

func (*Resource) Trace

func (rs *Resource) Trace(methodOperation MethodOperation, ct ContentTypes) *Method

Trace adds a new TRACE method to the method collection

func (*Resource) Use added in v0.4.0

func (rs *Resource) Use(m ...Middleware)

Use adds one or more middlewares to the resources's middleware stack. This middleware stack will be applied to the resource methods declared after the call of `Use`. The stack will be passed down to the child resources.

type ResourceCollection

type ResourceCollection struct {
	// contains filtered or unexported fields
}

ResourceCollection encapsulate a collection of resource nodes and the methods to add new ones. Each node name is unique, in case of conflict the new node will replace the old one silently

func (*ResourceCollection) Resource

func (rs *ResourceCollection) Resource(name string, fn func(r *Resource))

Resource creates a new resource node and append resources defined in fn function to the collection of resources to the new resource node. The usage for the method is as follows:

r := rest.NewResource("root")
r.Resource("parent", func(r *rest.Resource) {
	r.Resource("child1", func(r *rest.Resource) {
	})
r.Resource("child2", func(r *rest.Resource) {
	})
})

func (*ResourceCollection) ResourceP added in v0.7.0

func (rs *ResourceCollection) ResourceP(p Parameter, fn func(r *Resource))

ResourceP adds a new Resource with a URI parameter path. p Parameter must be URIParameter type, use NewURIParameter to create one.

func (*ResourceCollection) Resources

func (rs *ResourceCollection) Resources() []Resource

Resources returns the collection of the resource nodes. The order of the elements will not be consistent.

type Response

type Response struct {
	MutableResponseBody
	// contains filtered or unexported fields
}

Response represents a HTTP response. MutableResponseBody is an interface that represents the Http body response, that can mutate after a validation or an operation, taking the outputs of this methods as inputs.

func NewResponse

func NewResponse(code int) Response

NewResponse returns a Response with the specified code.

func (Response) Body

func (r Response) Body() interface{}

Body returns the MutableResponseBody property. In the case of a body that was set with WithBody or WithOperationResultBody methods, it will return the given 'body' parameter.

func (Response) Code

func (r Response) Code() int

Code returns the code property

func (Response) Description

func (r Response) Description() string

Description returns the description property

func (Response) WithBody

func (r Response) WithBody(body interface{}) Response

WithBody will set a static body property. It generates a dummy MutableResponseBody implementation under the hood, that will return the given 'body' parameter without change it.

func (Response) WithDescription

func (r Response) WithDescription(description string) Response

WithDescription will set description property.

func (Response) WithMutableBody

func (r Response) WithMutableBody(mutableResponseBody MutableResponseBody) Response

WithMutableBody will set the MutableResponseBody implementation. This will be used to mutate the result body, using the result values of validation or an operation as inputs. The struct of MutableResponseBody implementation will be used as response body for the specification.

func (Response) WithOperationResultBody

func (r Response) WithOperationResultBody(body interface{}) Response

WithOperationResultBody will set the body property. It generates a MutableResponseBody implementation under the hood, that will take the body result of an Operation as the response body. The given body parameter will be used for the specification only.

type Security

type Security struct {
	SecuritySchemes []*SecurityScheme
}

Security is the container of one or more SecurityScheme. One SecurityScheme will follow an `and` logic with other schemes in the same Security, this mean that the user need to pass all the SecuritySchemes defined in the same Security.

type SecurityOperation

type SecurityOperation struct {
	Authenticator
	FailedAuthenticationResponse Response
	FailedAuthorizationResponse  Response
}

SecurityOperation wraps the authentication/authorization method, and the respective fail responses

type SecurityScheme added in v0.3.0

type SecurityScheme struct {
	Type        string
	Name        string
	Description string
	Parameter   Parameter
	SecurityOperation
	OAuth2Flows []OAuth2Flow
}

SecurityScheme contains the authentication and authorization data, and methods.

func NewAPIKeySecurityScheme added in v0.3.0

func NewAPIKeySecurityScheme(name string, p Parameter, securityOperation SecurityOperation) *SecurityScheme

NewAPIKeySecurityScheme creates a new security scheme of APIKeySecurityType type.

func NewOAuth2SecurityScheme added in v0.3.0

func NewOAuth2SecurityScheme(name string, securityOperation SecurityOperation) *SecurityScheme

NewOAuth2SecurityScheme creates a new security scheme of OAuth2SecurityType type

func NewSecurityScheme added in v0.3.0

func NewSecurityScheme(name string, securityType string, securityOperation SecurityOperation) *SecurityScheme

NewSecurityScheme creates a new security scheme This should serve for specification purposes only, and you should provide the security through middleware implementation. If you want to enforce the security you must turn the Enforce property to true.

func (*SecurityScheme) WithAuthCodeOAuth2Flow added in v0.3.0

func (s *SecurityScheme) WithAuthCodeOAuth2Flow(authorizationURL, tokenURL string, scopes map[string]string) *SecurityScheme

WithAuthCodeOAuth2Flow adds a new oauth2 flow of authorization_code type with the necessary parameters

func (*SecurityScheme) WithClientCredentialOAuth2Flow added in v0.3.0

func (s *SecurityScheme) WithClientCredentialOAuth2Flow(tokenURL string, scopes map[string]string) *SecurityScheme

WithClientCredentialOAuth2Flow adds a new oauth2 flow of client_credential type with the necessary parameters

func (*SecurityScheme) WithImplicitOAuth2Flow added in v0.3.0

func (s *SecurityScheme) WithImplicitOAuth2Flow(authorizationURL string, scopes map[string]string) *SecurityScheme

WithImplicitOAuth2Flow adds a new oauth2 flow of implicit type with the necessary parameters

func (*SecurityScheme) WithOAuth2Flow added in v0.3.0

func (s *SecurityScheme) WithOAuth2Flow(flow OAuth2Flow) *SecurityScheme

WithOAuth2Flow adds a new oauth2 flow

func (*SecurityScheme) WithPasswordOAuth2Flow added in v0.3.0

func (s *SecurityScheme) WithPasswordOAuth2Flow(tokenURL string, scopes map[string]string) *SecurityScheme

WithPasswordOAuth2Flow adds a new oauth2 flow of password type with the necessary parameters

type ServerGenerator

type ServerGenerator interface {
	GenerateServer(api API) http.Handler
	GetURIParam() func(r *http.Request, key string) string
}

ServerGenerator interface describes the methods for generating the server and how to get the URI parameter.

type Validation added in v0.1.0

type Validation struct {
	Validator
	Response Response
}

type Validator

type Validator interface {
	Validate(Input) error
}

Validator type implementation will provide a method that validates the given Input.

type ValidatorFunc

type ValidatorFunc func(i Input) error

The ValidatorFunc type is an adapter to allow the use of ordinary functions as Validator. If f is a function with the appropriate signature, ValidatorFunc(f) is a Validator that calls f.

func (ValidatorFunc) Validate

func (f ValidatorFunc) Validate(i Input) error

Validate calls f(i)

Directories

Path Synopsis
_example
generator
test

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL