vial

package module
v0.3.4 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2020 License: MIT Imports: 25 Imported by: 0

README

Vial

Description

Vial is a microframework heavily inspired by flask designed to be REST-y and familiar to help facilitate microservice development in a familiar fashion.

Basic Usage Example

As a simple use case let's create an ultra simple controller that simply responds to a path at hello/<name> and responds to the provided name.

package main

import (
    "github.com/daihasso/vial"
    "github.com/daihasso/vial/neterr"
    "github.com/daihasso/vial/responses"
)

func main() {
    server, err := vial.NewServerDefault()
    if err != nil {
        panic(err)
    }

    server.AddController(
        "/hello/<name>",
        vial.FuncHandler(
            "get",
            func(transactor *vial.Transactor) responses.Data {
                name, ok := transactor.Request.PathString("name")
                if !ok {
                    return transactor.Abort(
                        500,
                        neterr.NewCodedError(
                            1,
                            "Could not retrieve name from path",
                        ),
                    )
                }

                return transactor.Respond(
                    200,
                    responses.Body(map[string]string{
                        "hello": name,
                    }),
                )
            },
        ),
    )

    err := server.Start() // Blocking

    if err != nil {
        panic(err)
    }
}

Making sense yet? Let's break it down a little to get a better understanding.

First:

server, err := vial.NewServerDefault()

This one is pretty straightforward; this creates our vial server instance and does some housekeeping tasks like reading an existing config or generating a default config in its absence, etc. By default the server will host on 127.0.0.1:8080.

Now comes the meat:

server.AddController(
    "/hello/<name>",
    vial.FuncHandler(
        "get",
        func(transactor *vial.Transactor) responses.Data {
            name, ok := transactor.Request.PathString("name")
            if !ok {
                return transactor.Abort(
                    500,
                    neterr.NewCodedError(
                        1,
                        "Could not retrieve name from path",
                    ),
                )
            }

            return transactor.Respond(
                200,
                responses.Body(map[string]string{
                    "hello": name,
                }),
            )
        },
    ),
)

Here we declare our actual controller for our route. First we pass in the route with "/hello/<name>" which responds to any /hello/foo route and grabs the value of foo and throws it in the path parameter map which we access later with the name, ok := transactor.Request.PathString("name") call.

Next we provide our method then the actual controller function. When using a pure functional handler we use the vial.FuncHandler which just maps a function to one or more HTTP methods (in our case GET defined by "get" as the first argument to FuncHandler). * Note: There is also a FuncControllerMulti that lets you define multiple methods for a single functional controller for convenience.

Our function signature in this case looks like func(transactor *vial.Transactor) responses.Data, there are multiple acceptable signatures which you can read more about here.

The Transactor we receive as an argument here is a kind of a multi-use tool for handling interactions within a handler. It helps with things like grabbing path parameters, setting headers, serializing data and more. You can read more about Transactor here here

In this case we first grab our name variable from the path with:

name, ok := transactor.Request.PathString("name")

The next part is some pretty standard boiler plate "If we don't get the path param we expect, return an error".

return transactor.Abort(
    500,
    neterr.NewCodedError(
        1,
        "Could not retrieve name from path",
    ),
)

The Abort function on transactor aborts the current request with the given error code and provides one or more CodedErrors. CodedError is a simple type which is just a code (some integer) and a message describing the error. The idea is simple, have coded, explanatory errors every time you abort a request so that your API users have entropy to understand why things went wrong.

Finally we respond with our message and a response code and a body:

return transactor.Respond(
    200,
    responses.Body(map[string]string{
        "hello": name,
    }),
)

The first argument to Respond is always a response code. You can simply respond with only a response code, but that wouldn't be very interesting so you probably want to add something in the response. There are a list of available optional parameters which add body, headers, etc to the response. Read more about these optional parameters here. Here we use responses.Body to add a body (any interface) to the response. If the body is something other than a string or a []byte object then it will be serialized in the manor appropriate for the specified encoding. Read more about encoding types here (By default a new server uses JSON as the default encoding type).

Now, if you run the above code and fire up your favorite web requester (we like HTTPie) and request 127.0.0.1:8080/hello/tester you will receive something like:

{
    "hello": "tester"
}

Struct Controllers

Controllers used by a Server can be either funcs as seen above used by vial.FuncHandler but they can also be controllers like so:

package main

import (
    "github.com/daihasso/vial"
    "github.com/daihasso/vial/responses"
)

type MyController struct {
    AppName string
}

func (self MyController) Get(transactor *vial.Transactor) responses.Data {
    return transactor.Respond(
        200,
        responses.Body(map[string]string{
            "app_name": self.AppName,
        }),
    )
}

func main() {
    server, err := vial.NewServer()
    if err != nil {
        panic(err)
    }

    server.AddController(
        "/test",
        &MyController{
            AppName: "TestServer",
        },
    )

    err = server.Start() // Blocking

    if err != nil {
        panic(err)
    }
}
package main

import (
    "github.com/daihasso/vial"
    "github.com/daihasso/vial/neterr"
)

type MyController struct {
    AppName string
}

func (self MyController) Get(transactor *Transactor) responses.Data {
    return transactor.Respond(
        200,
        responses.Body(map[string]string{
            "app_name": self.AppName,
        }),
    )
}

func main() {
    server, err := vial.NewServerDefault()
    if err != nil {
        panic(err)
    }

    server.AddController(
        "/test",
        &MyController{
            AppName: "TestServer",
        },
    )

    err := server.Start() // Blocking

    if err != nil {
        panic(err)
    }
}

Now fire a request to 127.0.0.1:8080/test and you should get something back like:

{
    "app_name": "TestServer"
}

Obviously this example is rather contrived but using a struct has other benefits such as grouping controllers around routes, and more complex logic and variable tracking. At the end of the day both are first-class citizens for Vial so make your choice whatever way feels comfortable for you.

The Sequence ID

A Sequence ID is an id that is either grabbed from a header value of Sequence-Id passed in with the request or it is generated at the start of the request. It is then used to identify further actions down the chain of as a result of the request. It is a first-class citizen in the vial framework and is added to the context upon the start of the request under the vial.sequence_id key. It is also available via the Transactor.SequenceId() method as well as it being set as a DefaultExtra on the Transactor.Logger object.

Its primary purpose is to keep track of information on a given request and should be passed to any thing that produces logs or any subsequent API calls made to other servers. The Sequence ID will also be returned in the headers for the request to the api so that the caller can utilize it or a developer can use it to trace a request in an error case.

Path Parameters

Vial has a path parameter parsing library that lets you define specific matches in the declaration of your url such as:

  • float - <integer:var_name>
  • intger - <integer:var_name>
  • UUID - <uuid:var_name>
  • string - <string:var_name> or <var_name>

These can be accessed off the request (through the transactor) and auto-coerced into appropriate formats with:

  • transactor.Request.PathFloat
  • transactor.Request.PathInteger
  • transactor.Request.PathUUID
  • transactor.Request.PathString

Any url that doesn't match the expected format will be rejected and another matcher will be attempted if it exists. In other-words you can have two routes: /image/<integer:id> and /image/<uuid:id> And both will be matched to the appropriate calls.

Documentation

Index

Constants

View Source
const (
	SequenceIdHeader string = "Sequence-Id"
)

This is a set of all the headers considered default for the networking stack.

Variables

View Source
var ContextKeyBase = "vial."

This is the context base-key for all vial context keys.

View Source
var FloatPathParamMatcher = &PathParamMatcher{
	Identifiers: []string{"float"},
	RegexString: `[0-9]*\.[0-9]+`,
	Coercer: func(stringVal string) (interface{}, error) {
		return strconv.ParseFloat(stringVal, 64)
	},
}

FloatPathParamMatcher matches only whole floats numbers. Floats are defined as having at least a decimal value.

View Source
var IntPathParamMatcher = &PathParamMatcher{
	Identifiers: []string{"int", "integer"},
	RegexString: `[0-9]+`,
	Coercer: func(stringVal string) (interface{}, error) {
		return strconv.Atoi(stringVal)
	},
}

IntPathParamMatcher matches only whole integers.

View Source
var RequestIdContextKey = ContextKey("request_id")

This is the key that the Sequence ID is stored under in the context.

View Source
var SequenceIdContextKey = ContextKey("sequence_id")

This is the key that the Sequence ID is stored under in the context.

View Source
var ServerContextKey = ContextKey("server")

This is the key that the server is stored under.

View Source
var ServerLoggerContextKey = ContextKey("server.logger")

This is the key that the server's logger is stored under.

View Source
var StringPathParamMatcher = &PathParamMatcher{
	Identifiers: []string{"string", ""},
	RegexString: `[^\/\\]+`,
	Coercer: func(stringVal string) (interface{}, error) {
		return stringVal, nil
	},
}

StringPathParamMatcher is the most basic PathParamMatcher that simply matches any non-forward-slash character. It is also the default behaviour.

View Source
var TransactorContextKey = ContextKey("transactor")

This is the key that the transactor will live under in the request context.

View Source
var UUIDPathParamMatcher = &PathParamMatcher{
	Identifiers: []string{"uuid"},
	RegexString: `[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?` +
		`[0-9a-fA-F]{4}-?[0-9a-fA-F]{12}`,
	Coercer: func(stringVal string) (interface{}, error) {
		return uuid.Parse(stringVal)
	},
}

UUIDPathParamMatcher matches the generic UUID format and uses google's UUID library to convert the uuid string to a uuid.UUID.

Functions

func AddPathParamMatcher added in v0.2.0

func AddPathParamMatcher(newMatcher *PathParamMatcher)

AddPathParamMatcher adds a new path param matcher to the global registry.

func ContextKey

func ContextKey(key string) string

ContextKey is a helper for generating a context key prefixed for vial.

func ContextRequestId added in v0.2.5

func ContextRequestId(ctx context.Context) (*uuid.UUID, error)

func ContextSequenceId

func ContextSequenceId(ctx context.Context) (*uuid.UUID, error)

ContextSequenceId tries to retrieve a Sequence ID stored in the provided context and returns it if it exists.

func ContextWithSequenceId

func ContextWithSequenceId(
	ctx context.Context, sequenceId uuid.UUID,
) context.Context

ContextWithSequenceId creates a new context with the provided Sequence ID inserted into it.

func DefaultOptions

func DefaultOptions(
	server Server,
	transactor *Transactor,
	methods []*RouteControllerHelper,
) responses.Data

DefaultOptions iterates a routes available methods and returns them in the header.

func FuncHandler

func FuncHandler(
	method string, rcf RouteControllerFunc,
) methodControllerFunc

FuncHandler wraps a functional method handler with the method it responds to.

func FuncHandlerMulti

func FuncHandlerMulti(
	rcf RouteControllerFunc, method string, otherMethods ...string,
) methodControllerFunc

FuncHandlerMulti wraps a functional method handler with a series of methods it responds to.

func IsPathParamDoesNotExist added in v0.2.0

func IsPathParamDoesNotExist(err error) bool

IsPathParamDoesNotExist checks if an error is caused by the param not existing.

func IsWrongPathParamType added in v0.2.0

func IsWrongPathParamType(err error) bool

IsWrongPathParamType checks if an error is caused by the type requested not being the correct type.

func MethodsForRouteController

func MethodsForRouteController(
	path string,
	routeControllers ...RouteController,
) (map[RequestMethod]RouteControllerCaller, map[reflect.Value]string)

MethodsForRouteController gets all the methods that a RouteController has available. NOTE: This method implicitly makes the assumption that the first controllers

take presidence (i.e. If both controller 1 and controller 5 respond to
the GET method then controller 1 will be the controller chosen).

func RouteControllerIsValid

func RouteControllerIsValid(rc RouteController) []string

RouteControllerIsValid checks a RouteController to see if it meets some of of the expectations of a RouteController.

Types

type Config

type Config struct {
	Swagger struct {
		Path string
	}
	Host string
	Port int
	Tls  struct {
		CertPath,
		KeyPath string
		Enabled bool
	}
	Jwt struct {
		EncryptionKey,
		HmacKey string
	}
}

type InboundRequest

type InboundRequest struct {
	http.Request
	PathParams PathParams
}

InboundRequest is a (thin) wrapper around http.Request.

func NewInboundRequest added in v0.2.0

func NewInboundRequest(
	baseRequest *http.Request,
	pathParams PathParams,
) *InboundRequest

NewInboundRequest gets a request based on an existing HTTP request with path parameters included.

func (*InboundRequest) PathFloat added in v0.2.0

func (r *InboundRequest) PathFloat(key string) (float64, bool)

PathInt returns a path variable as a int or an error if it could not be found or could not be converted.

func (*InboundRequest) PathInt added in v0.2.0

func (r *InboundRequest) PathInt(key string) (int, bool)

PathInt returns a path variable as a int or an error if it could not be found or could not be converted.

func (InboundRequest) PathString added in v0.2.0

func (r InboundRequest) PathString(key string) (string, bool)

PathString returns a variable from the path matching the provided key as a string.

func (*InboundRequest) PathUUID added in v0.2.0

func (r *InboundRequest) PathUUID(key string) (uuid.UUID, bool)

PathUUID returns a path variable as a UUID or an error if it could not be found or could not be converted.

func (*InboundRequest) QueryParam added in v0.2.0

func (r *InboundRequest) QueryParam(key string) (string, bool)

QueryParam returns a parameter from the query parameters using the first result if there are many.

func (*InboundRequest) QueryParamMultiple added in v0.2.0

func (r *InboundRequest) QueryParamMultiple(key string) ([]string, bool)

QueryParamMultiple returns a parameter from the query parameters as a slice of all the results.

func (InboundRequest) QueryParams added in v0.2.0

func (r InboundRequest) QueryParams() map[string][]string

QueryParams returns the raw query params map.

func (InboundRequest) WithContext added in v0.2.2

func (r InboundRequest) WithContext(ctx context.Context) *InboundRequest

WithContext returns a new InboundRequest with the provided context.

type PathParamCoercer added in v0.2.0

type PathParamCoercer func(string) (interface{}, error)

PathParamCoercer is a function which takes a raw path param string value and converts it to the expected value.

type PathParamMatcher added in v0.2.0

type PathParamMatcher struct {
	// Identifiers is a list of all the aliases that this path parameter,
	// matches in a route definition such as <int:id> where int is an
	// identifier.
	Identifiers []string

	// RegexString is a string containing a regex that matches this type of
	// PathParam.
	RegexString string

	// Coercer as specified above takes a string value and returns it's
	// coerced value.
	Coercer PathParamCoercer
}

PathParamsMatcher is a matcher for a path parameter specified in the <type:var> part of a route.

func GetPathParamMatcher added in v0.2.0

func GetPathParamMatcher(identifier string) (*PathParamMatcher, bool)

GetPathParamMatcher retrieves a PathParamMatcher for a given identifier.

type PathParams added in v0.2.0

type PathParams map[string]interface{}

PathParams is a convenience wrapper around a map holding coerced path values.

func (PathParams) Float added in v0.2.0

func (self PathParams) Float(key string) (float64, error)

Float retrieves and coerces a float.

func (PathParams) Int added in v0.2.0

func (self PathParams) Int(key string) (int, error)

Int retrieves and coerces a int.

func (PathParams) String added in v0.2.0

func (self PathParams) String(key string) (string, error)

String retrieves and coerces a string.

func (PathParams) UUID added in v0.2.0

func (self PathParams) UUID(key string) (uuid.UUID, error)

UUID retrieves and coerces a UUID.

type PostMiddleWare

type PostMiddleWare func(
	context.Context, *Transactor, responses.Data,
) (*responses.Data, error)

PostMiddleWare is a function that's run against a request after the route's primary function is performed.

type PreMiddleWare

type PreMiddleWare func(context.Context, *Transactor) (
	*responses.Data, *context.Context, error,
)

PreMiddleWare is a function that's run against a request before the route's primary function is performed. Returning a Data struct will short-circut the response and use this response instead of processing the normal handler. Returning a context will make that the new context for future middleware or handlers.

func DefaultEncryptionHeadersMiddleware

func DefaultEncryptionHeadersMiddleware() PreMiddleWare

type RequestMethod

type RequestMethod int

RequestMethod is a method of request (i.e: GET).

const (
	MethodUnknown RequestMethod

	MethodGET
	MethodPUT
	MethodPOST
	MethodDELETE
	MethodOPTIONS
	MethodHEAD
	MethodPATCH
)

Describes all the RequestMethods.

func RequestMethodFromString

func RequestMethodFromString(method string) RequestMethod

RequestMethodFromString converts a string HTTP method to a RequestMethod enum.

func (RequestMethod) String

func (self RequestMethod) String() string

RequestMethodFromString converts a string HTTP method to a RequestMethod enum.

type Route

type Route struct {
	Base string
	// contains filtered or unexported fields
}

Route is a broken-down version of a route string.

func ParseRoute

func ParseRoute(route string) (newRoute Route, err error)

ParseRoute parses a route string with path param variable matchers into a Route struct.

func (Route) Matches

func (r Route) Matches(url string) bool

Matches will check if a url matches the route definition.

func (Route) PathParams

func (r Route) PathParams(url string) (PathParams, error)

PathParams will take a url and parse the variables according to the route definition.

type RouteController

type RouteController interface{}

A RouteController is a controller for a given route that defines the methods it responds to.

type RouteControllerCaller

type RouteControllerCaller func(context.Context, *Transactor) responses.Data

RouteControllerCaller provides a uniform function for calling any of the controller function variants.

type RouteControllerFunc

type RouteControllerFunc interface{}

A RouteControllerFunc is a functional controller for a given route & method that defines the methods it responds to.

type RouteControllerHelper

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

RouteControllerHelper is a wrapper around a RouteController that stores its methods and the route it's attached to.

func (RouteControllerHelper) AllMethods

func (self RouteControllerHelper) AllMethods() []RequestMethod

AllMethods returns all the methods the RouteControllerCaller responds to.

func (RouteControllerHelper) ControllerFuncForMethod

func (self RouteControllerHelper) ControllerFuncForMethod(
	m RequestMethod,
) (RouteControllerCaller, bool)

ControllerFuncForMethod will return the correct function for a given HTTP method. This method expects you to only call methods that are defined. Use RespondsToMethod to check before calling this function.

func (RouteControllerHelper) RespondsToMethod

func (self RouteControllerHelper) RespondsToMethod(m RequestMethod) bool

RespondsToMethod checks if the RouteController this helper wraps responds to the given method.

func (RouteControllerHelper) RespondsToMethodString

func (self RouteControllerHelper) RespondsToMethodString(
	methodString string,
) bool

RespondsToMethodString checks if the RouteController this helper wraps responds to the given method string.

type RouteControllerMethod

type RouteControllerMethod func(context.Context, *Transactor) responses.Data

A RouteControllerMethod is a function which takes a context and a transactor and handles the request.

type RouteControllerMethodMinimal

type RouteControllerMethodMinimal func(*Transactor) responses.Data

A RouteControllerMethodMinimal is a function which takes only a transactor and handles the request.

type RouteFunction added in v0.3.4

type RouteFunction func(transactor *Transactor) responses.Data

func ContextOnly added in v0.3.4

func ContextOnly(
	controller func(context.Context) responses.Data,
) RouteFunction

func WithContext added in v0.3.4

func WithContext(
	controller func(context.Context, *Transactor) responses.Data,
) RouteFunction

type Server

type Server struct {
	PathReader *peechee.PathReader
	Logger     *logging.Logger
	// contains filtered or unexported fields
}

Server is a specialized server for microservices.

func NewServer

func NewServer(options ...ServerOption) (*Server, error)

NewServer creates a bare-bones server.

func NewServerDefault

func NewServerDefault(options ...ServerOption) (*Server, error)

NewServerDefault creates a new server with (mostly) sensible defaults.

func (*Server) AddController

func (s *Server) AddController(
	path string,
	rc RouteController,
	otherRCs ...RouteController,
) error

AddController adds a new controller to the server at the route specified. It must match the expected format that RouteControllerIsValid checks for. It must be one of:

A func or a struct with a method defined in validRouteControllerFields
(Post, Get, Put, Patch, Delete, Head and/or Options) that
matches either of the signatures defined in validRouteControllerTypes:
    func(context.Context, *Transactor) responses.Data
or
    func(*Transactor) responses.Data

func (*Server) AddPostActionMiddleware added in v0.3.3

func (self *Server) AddPostActionMiddleware(middleware ...PostMiddleWare)

func (*Server) AddPreActionMiddleware added in v0.3.3

func (self *Server) AddPreActionMiddleware(middleware ...PreMiddleWare)

func (*Server) All added in v0.3.4

func (self *Server) All(
	path string, callback RouteFunction, otherCallbacks ...RouteFunction,
) error

func (*Server) Delete added in v0.3.4

func (self *Server) Delete(
	path string, callback RouteFunction, otherCallbacks ...RouteFunction,
) error

func (*Server) Get added in v0.3.4

func (self *Server) Get(
	path string, callback RouteFunction, otherCallbacks ...RouteFunction,
) error

func (Server) GetConfig

func (self Server) GetConfig() Config

GetConfig retrieves the config by value.

func (*Server) GoStart

func (self *Server) GoStart() chan ServerChannelResponse

GoStart starts the server. This call is non-blocking.

func (*Server) Head added in v0.3.4

func (self *Server) Head(
	path string, callback RouteFunction, otherCallbacks ...RouteFunction,
) error

func (*Server) Options added in v0.3.4

func (self *Server) Options(
	path string, callback RouteFunction, otherCallbacks ...RouteFunction,
) error

func (*Server) Patch added in v0.3.4

func (self *Server) Patch(
	path string, callback RouteFunction, otherCallbacks ...RouteFunction,
) error

func (*Server) Post added in v0.3.4

func (self *Server) Post(
	path string, callback RouteFunction, otherCallbacks ...RouteFunction,
) error

func (*Server) Put added in v0.3.4

func (self *Server) Put(
	path string, callback RouteFunction, otherCallbacks ...RouteFunction,
) error

func (*Server) Start

func (s *Server) Start() error

Start starts the server. This call is blocking.

func (*Server) Stop

func (s *Server) Stop() error

Stop stops the server.

func (Server) UrlFor added in v0.3.0

func (self Server) UrlFor(handler interface{}) string

func (Server) UrlsFor added in v0.3.0

func (self Server) UrlsFor(handler interface{}) []string

type ServerChannelResponse

type ServerChannelResponse struct {
	Type  ServerChannelResponseType
	Error error
}

type ServerChannelResponseType

type ServerChannelResponseType int
const (
	UnknownChannelResponse ServerChannelResponseType = iota
	ServerStartChannelResponse
	ServerShutdownChannelResponse
	UnknownErrorChannelResponse
)

type ServerOption

type ServerOption func(*serverOptions) error

ServerOption is a n option applied to the server.

func AddConfig

func AddConfig(config *Config) ServerOption

AddConfig sets the server config to the provided config.

func AddConfigFromFile

func AddConfigFromFile(configFilePath string) ServerOption

AddConfig reads a config from a file under the `vial:` key in a config file at the provided path.

func AddCustomLogger

func AddCustomLogger(logger *logging.Logger) ServerOption

AddCustomLogger will set the server logger to the provided logger.

func AddDefaultHealthRoute

func AddDefaultHealthRoute() ServerOption

AddDefaultHealthRoute adds an ultra-simple health route that simple returns a JSON payload with `{ "healthy": true }` This route is included in NewServerDefault automatically.

func AddDefaultSwaggerRoute

func AddDefaultSwaggerRoute(formats ...SwaggerFormat) ServerOption

AddDefaultSwaggerRoute adds the default swagger route to the server. This route is included in NewServerDefault automatically.

func AddEncryption

func AddEncryption(certData, keyData io.Reader) ServerOption

AddEncryption adds encryption to the server with the provided cert/key data.

func AddEncryptionFilePaths

func AddEncryptionFilePaths(certPath, keyPath string) ServerOption

AddEncryptionFilePaths adds encryption to the server with the key/cert data at the provided paths.

func AddPostActionMiddleware

func AddPostActionMiddleware(middlewares ...PostMiddleWare) ServerOption

AddPostActionMiddleware runs the provided middleware(s) against the server after every request is handled but before it is returned to the requestor.

func AddPreActionMiddleware

func AddPreActionMiddleware(middlewares ...PreMiddleWare) ServerOption

AddPreActionMiddleware runs the provided middleware(s) against the server before every request is handled.

func SetDefaultEncoding

func SetDefaultEncoding(encodingType responses.EncodingType) ServerOption

SetDefaultEncoding will set the server-wide default encoding scheme.

func SetPathReader

func SetPathReader(pathReader *peechee.PathReader) ServerOption

SetPathReader overrides the default PathReader with a custom one.

type SwaggerFormat

type SwaggerFormat int
const (
	SwaggerYamlFormat SwaggerFormat
	SwaggerJsonFormat
)

type Transactor

type Transactor struct {
	Builder *responses.Builder
	Config  *Config
	Logger  *logging.Logger
	Request *InboundRequest
}

Transactor is a helper for handling request and response logic.

func NewTransactor

func NewTransactor(
	request *http.Request,
	responseWriter http.ResponseWriter,
	variables PathParams,
	config *Config,
	logger *logging.Logger,
	encodingType responses.EncodingType,
	options ...TransactorOption,
) (*Transactor, error)

NewTransactor will generate a new transactor for request to a controller.

func (Transactor) Abort

func (self Transactor) Abort(
	statusCode int,
	codedErr neterr.CodedError,
	otherErrors ...neterr.CodedError,
) responses.Data

Abort is a shortcut for responding to a request with a failure.

func (*Transactor) AddHeader

func (t *Transactor) AddHeader(key string, content interface{}) error

AddHeader marshales content and adds it as a header key.

func (*Transactor) ChangeContext added in v0.2.2

func (self *Transactor) ChangeContext(ctx context.Context)

ChangeContext changes the existing context on the transactor to the provided one. Use this with caution.

func (Transactor) Context added in v0.2.2

func (self Transactor) Context() context.Context

Context is a helper for retrieving the request context.

func (*Transactor) CopyHeadersFromResponse

func (t *Transactor) CopyHeadersFromResponse(
	response *http.Response,
)

CopyHeadersFromResponse will copy the headers from a client response into the server response.

func (*Transactor) RequestBodyString

func (i *Transactor) RequestBodyString() (string, error)

RequestBodyString return the request body as a string.

func (Transactor) Respond

func (self Transactor) Respond(
	statusCode int, attributes ...responses.AdditionalAttribute,
) responses.Data

Respond is a shortcut for finishing and responding to a request.

func (Transactor) SequenceId

func (self Transactor) SequenceId() *uuid.UUID

SequenceId grabs the current Sequence ID from the context.

func (*Transactor) SetHeader

func (t *Transactor) SetHeader(key string, content interface{}) error

SetHeader marshales content and sets key's content to it.

func (Transactor) UrlFor added in v0.3.0

func (self Transactor) UrlFor(
	handler interface{}, vals ...interface{},
) string

type TransactorOption

type TransactorOption func(*Transactor) error

TransctorOption is an option for a Transactor.

func WithExistingContext

func WithExistingContext(existingCtx context.Context) TransactorOption

WithExistingContext creates a transactor using the existing context which overrides the default `request.Context()`.

type UrlParamValues added in v0.3.0

type UrlParamValues map[string]interface{}

UrlParamValues is a helper for providing key: values for writing values to a url with parameters.

Directories

Path Synopsis
Package neterr seeks to unify error formatting for API consumers.
Package neterr seeks to unify error formatting for API consumers.
Package responses handles common response logic and helpers for constructing and managing responses.
Package responses handles common response logic and helpers for constructing and managing responses.

Jump to

Keyboard shortcuts

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