web

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2019 License: MIT Imports: 13 Imported by: 0

README

web

Package web provides a set of tools and abstractions to enable HTTP applications to scale while maintaining readability.

Usage Example

// Ping :: GET /ping
type Ping struct{}

var _ web.Route = &Ping{}

// Method returns the route method.
func (*Ping) Method() string {
    return http.MethodGet
}

// Path returns the route path.
func (*Ping) Path() string {
    return "/ping"
}

// Middleware returns the middleware for the route.
func (*Ping) Middleware() []web.Middleware {
    return nil
}

// Handle is the handler for the route.
func (*Ping) Handle(ctx *web.Context) {
    responseModel := &models.PingResponseModel{
        Now: time.Now(),
    }

    ctx.RespondWithJSON(http.StatusOK, responseModel)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ByteSizeToFriendlyString

func ByteSizeToFriendlyString(length int64) string

ByteSizeToFriendlyString returns the provided byte length as a human-friendly string e.g. 1024 => 1.00 kB.

func UnmarshalFromResponseRecorder

func UnmarshalFromResponseRecorder(w *httptest.ResponseRecorder, model interface{}) error

UnmarshalFromResponseRecorder unmarshals the body of a response recorder in unit tests.

Types

type Context

type Context struct {
	Request *http.Request
	// contains filtered or unexported fields
}

Context contains contextual items for a single HTTP request as well as defines utility methods for interacting with these contextual items.

func NewContext

func NewContext(w http.ResponseWriter, r *http.Request, c di.Container, logger log.Logger) *Context

NewContext creates a new context for the provided request, di.Container and logger.

func (*Context) AssertContentLength

func (ctx *Context) AssertContentLength(max int64) bool

AssertContentLength ensures that a content length was provided, and that it is in (0, max].

func (*Context) AssertContentType

func (ctx *Context) AssertContentType(allowedContentTypes ...string) bool

AssertContentType ensures that the content type of the request matches one of the content types provided.

func (*Context) AssertMethod

func (ctx *Context) AssertMethod(allowedMethods ...string) bool

AssertMethod ensures that the incoming request is using one of the provided methods.

func (*Context) FromJSON

func (ctx *Context) FromJSON(model Purifiable) bool

FromJSON retrieves JSON from the request body to place into the provided Purifiable.

func (*Context) GetCorrelationID

func (ctx *Context) GetCorrelationID() id.ID

GetCorrelationID returns the correlation ID for this request.

func (*Context) GetMiddlewareArtifact

func (ctx *Context) GetMiddlewareArtifact(name string) interface{}

GetMiddlewareArtifact returns the middleware artifact with the specified name. It will return nil if the artifact does not exist.

func (*Context) GetPathParameter

func (ctx *Context) GetPathParameter(name string) string

GetPathParameter retrieves a path segment parameter from the request.

func (*Context) GetQueryParameter

func (ctx *Context) GetQueryParameter(name string) string

GetQueryParameter retrieves a query parameter from the request.

func (*Context) Header

func (ctx *Context) Header() http.Header

Header gets the header set of the response.

func (*Context) InternalServerError added in v1.0.1

func (ctx *Context) InternalServerError(p interface{})

InternalServerError replies with a 500 Internal Server Error problem details.

func (*Context) NotFound

func (ctx *Context) NotFound(subjectType string, subject string)

NotFound replies with a 404 Not Found problem details.

func (*Context) Resolve

func (ctx *Context) Resolve(into interface{})

Resolve calls Resolve on the underlying container.

func (*Context) Respond

func (ctx *Context) Respond(code int)

Respond sets appropriate outgoing headers and the status code.

func (*Context) RespondWithJSON

func (ctx *Context) RespondWithJSON(code int, model trace.Traceable)

RespondWithJSON replies to the provided request with the provided traceable model.

func (*Context) SetDebuggingEnabled

func (ctx *Context) SetDebuggingEnabled(enabled bool)

SetDebuggingEnabled allows errors to pass through into problems produced by this context.

func (*Context) SetJSONContentLengthLimit

func (ctx *Context) SetJSONContentLengthLimit(limit int64)

SetJSONContentLengthLimit sets the JSON content length limit for use in the FromJSON method. By default, this value is 1 << 20.

func (*Context) SetMiddlewareArtifact

func (ctx *Context) SetMiddlewareArtifact(name string, value interface{})

SetMiddlewareArtifact sets the middleware artifact for the provided name.

func (*Context) SetProblemPrefix

func (ctx *Context) SetProblemPrefix(prefix string)

SetProblemPrefix sets the URL prefix for problem details types produced by this context.

func (*Context) Unauthorized

func (ctx *Context) Unauthorized(reason string)

Unauthorized replies with a 401 Unauthorized problem details.

func (*Context) Write

func (ctx *Context) Write(b []byte) (int, error)

Write writes to the underlying response writer.

type ContextHandlerFunc

type ContextHandlerFunc func(ctx *Context)

ContextHandlerFunc is an alias for a function that accepts a Context as its one and only parameter.

type HandlerBuilder

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

HandlerBuilder is used to build a handler that can be passed to any HTTP server. Once Build() has been called, the HandlerBuilder is invalid and can no longer be used. HandlerBuilder is not thread safe.

func NewHandlerBuilder

func NewHandlerBuilder(c di.Container, logger log.Logger) *HandlerBuilder

NewHandlerBuilder creates a new HandlerBuilder with the provided container and logger.

func (*HandlerBuilder) Build

func (hb *HandlerBuilder) Build() http.Handler

Build a computed handler for the current settings and with the provided routes.

func (*HandlerBuilder) SetDebuggingEnabled

func (hb *HandlerBuilder) SetDebuggingEnabled(debuggingEnabled bool)

SetDebuggingEnabled sets whether or not debugging is enabled.

func (*HandlerBuilder) SetJSONContentLengthLimit

func (hb *HandlerBuilder) SetJSONContentLengthLimit(jsonContentLengthLimit int64)

SetJSONContentLengthLimit sets the JSON content length limit for incoming JSON.

func (*HandlerBuilder) SetProblemPrefix

func (hb *HandlerBuilder) SetProblemPrefix(problemPrefix string)

SetProblemPrefix sets the problem details prefix.

func (*HandlerBuilder) Use

func (hb *HandlerBuilder) Use(route Route)

Use adds a route to the list of routes this handler should expose.

type MetricResponseWriter

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

MetricResponseWriter wraps a standard http.ResponseWriter with additional functionality. Specifically, it records the amount of data written, the response code, and the duration of the request/response.

func NewMetricResponseWriter

func NewMetricResponseWriter(w http.ResponseWriter) *MetricResponseWriter

NewMetricResponseWriter creates a new MetricResponseWriter with the provided underlying http.ResponseWriter.

func (*MetricResponseWriter) Duration

func (mrw *MetricResponseWriter) Duration() time.Duration

Duration returns the duration between the start of the request and now.

func (*MetricResponseWriter) HasWrittenHeaders

func (mrw *MetricResponseWriter) HasWrittenHeaders() bool

HasWrittenHeaders returns true if WriteHeader has been called.

func (*MetricResponseWriter) Header

func (mrw *MetricResponseWriter) Header() http.Header

Header simply returns the headers of the underlying response writer.

func (*MetricResponseWriter) StatusCode

func (mrw *MetricResponseWriter) StatusCode() int

StatusCode returns the status code that was written for the response. If the status code is yet to be written, or WriteHeader was never explicitly called, StatusCode will return http.StatusOK.

func (*MetricResponseWriter) Volume

func (mrw *MetricResponseWriter) Volume() int64

Volume returns the number of bytes written to the response writer body.

func (*MetricResponseWriter) Write

func (mrw *MetricResponseWriter) Write(b []byte) (int, error)

Write writes to the underlying response writer, recording the number of bytes successfully written.

func (*MetricResponseWriter) WriteHeader

func (mrw *MetricResponseWriter) WriteHeader(statusCode int)

WriteHeader records and writes the header if it has not already been written.

type Middleware

type Middleware interface {
	Handle(ctx *Context) bool
}

Middleware defines the methods that any HTTP middleware must implement. If the Handle method returns true, the request will continue to be propagated to subsequent middleware handlers and eventually the route handler.

type Purifiable

type Purifiable interface {
	trace.Traceable

	Purify() (string, error)
}

Purifiable defines the methods that any purifiable request model must implement. The intention is to allow request methods to be able to validate themselves - keeping the validation of user provided information out of routes. Purifiable models are implicitly trace.Redactable.

The first return value is the name of the invalid field, the second is the error describing the problem.

type Route

type Route interface {
	Method() string
	Path() string
	Middleware() []Middleware
	Handle(ctx *Context)
}

Route defines the methods that any HTTP route must implement.

Jump to

Keyboard shortcuts

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