http - ActiveState ActiveGo 1.8
...

Package http

import "github.com/go-kit/kit/transport/http"
Overview
Index
Examples

Overview ▾

Package http provides a general purpose HTTP binding for endpoints.

Index ▾

Constants
func DefaultErrorEncoder(_ context.Context, err error, w http.ResponseWriter)
func EncodeJSONRequest(c context.Context, r *http.Request, request interface{}) error
func EncodeJSONResponse(_ context.Context, w http.ResponseWriter, response interface{}) error
func EncodeXMLRequest(c context.Context, r *http.Request, request interface{}) error
func PopulateRequestContext(ctx context.Context, r *http.Request) context.Context
type Client
    func NewClient(method string, tgt *url.URL, enc EncodeRequestFunc, dec DecodeResponseFunc, options ...ClientOption) *Client
    func (c Client) Endpoint() endpoint.Endpoint
type ClientOption
    func BufferedStream(buffered bool) ClientOption
    func ClientAfter(after ...ClientResponseFunc) ClientOption
    func ClientBefore(before ...RequestFunc) ClientOption
    func SetClient(client *http.Client) ClientOption
type ClientResponseFunc
type DecodeRequestFunc
type DecodeResponseFunc
type EncodeRequestFunc
type EncodeResponseFunc
type ErrorEncoder
type Headerer
type RequestFunc
    func SetRequestHeader(key, val string) RequestFunc
type Server
    func NewServer(e endpoint.Endpoint, dec DecodeRequestFunc, enc EncodeResponseFunc, options ...ServerOption) *Server
    func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
type ServerFinalizerFunc
type ServerOption
    func ServerAfter(after ...ServerResponseFunc) ServerOption
    func ServerBefore(before ...RequestFunc) ServerOption
    func ServerErrorEncoder(ee ErrorEncoder) ServerOption
    func ServerErrorLogger(logger log.Logger) ServerOption
    func ServerFinalizer(f ServerFinalizerFunc) ServerOption
type ServerResponseFunc
    func SetContentType(contentType string) ServerResponseFunc
    func SetResponseHeader(key, val string) ServerResponseFunc
type StatusCoder

Package files

client.go doc.go encode_decode.go request_response_funcs.go server.go

Constants

const (
    // ContextKeyRequestMethod is populated in the context by
    // PopulateRequestContext. Its value is r.Method.
    ContextKeyRequestMethod contextKey = iota

    // ContextKeyRequestURI is populated in the context by
    // PopulateRequestContext. Its value is r.RequestURI.
    ContextKeyRequestURI

    // ContextKeyRequestPath is populated in the context by
    // PopulateRequestContext. Its value is r.URL.Path.
    ContextKeyRequestPath

    // ContextKeyRequestProto is populated in the context by
    // PopulateRequestContext. Its value is r.Proto.
    ContextKeyRequestProto

    // ContextKeyRequestHost is populated in the context by
    // PopulateRequestContext. Its value is r.Host.
    ContextKeyRequestHost

    // ContextKeyRequestRemoteAddr is populated in the context by
    // PopulateRequestContext. Its value is r.RemoteAddr.
    ContextKeyRequestRemoteAddr

    // ContextKeyRequestXForwardedFor is populated in the context by
    // PopulateRequestContext. Its value is r.Header.Get("X-Forwarded-For").
    ContextKeyRequestXForwardedFor

    // ContextKeyRequestXForwardedProto is populated in the context by
    // PopulateRequestContext. Its value is r.Header.Get("X-Forwarded-Proto").
    ContextKeyRequestXForwardedProto

    // ContextKeyRequestAuthorization is populated in the context by
    // PopulateRequestContext. Its value is r.Header.Get("Authorization").
    ContextKeyRequestAuthorization

    // ContextKeyRequestReferer is populated in the context by
    // PopulateRequestContext. Its value is r.Header.Get("Referer").
    ContextKeyRequestReferer

    // ContextKeyRequestUserAgent is populated in the context by
    // PopulateRequestContext. Its value is r.Header.Get("User-Agent").
    ContextKeyRequestUserAgent

    // ContextKeyRequestXRequestID is populated in the context by
    // PopulateRequestContext. Its value is r.Header.Get("X-Request-Id").
    ContextKeyRequestXRequestID

    // ContextKeyResponseHeaders is populated in the context whenever a
    // ServerFinalizerFunc is specified. Its value is of type http.Header, and
    // is captured only once the entire response has been written.
    ContextKeyResponseHeaders

    // ContextKeyResponseSize is populated in the context whenever a
    // ServerFinalizerFunc is specified. Its value is of type int64.
    ContextKeyResponseSize
)

func DefaultErrorEncoder

func DefaultErrorEncoder(_ context.Context, err error, w http.ResponseWriter)

DefaultErrorEncoder writes the error to the ResponseWriter, by default a content type of text/plain, a body of the plain text of the error, and a status code of 500. If the error implements Headerer, the provided headers will be applied to the response. If the error implements json.Marshaler, and the marshaling succeeds, a content type of application/json and the JSON encoded form of the error will be used. If the error implements StatusCoder, the provided StatusCode will be used instead of 500.

func EncodeJSONRequest

func EncodeJSONRequest(c context.Context, r *http.Request, request interface{}) error

EncodeJSONRequest is an EncodeRequestFunc that serializes the request as a JSON object to the Request body. Many JSON-over-HTTP services can use it as a sensible default. If the request implements Headerer, the provided headers will be applied to the request.

func EncodeJSONResponse

func EncodeJSONResponse(_ context.Context, w http.ResponseWriter, response interface{}) error

EncodeJSONResponse is a EncodeResponseFunc that serializes the response as a JSON object to the ResponseWriter. Many JSON-over-HTTP services can use it as a sensible default. If the response implements Headerer, the provided headers will be applied to the response. If the response implements StatusCoder, the provided StatusCode will be used instead of 200.

func EncodeXMLRequest

func EncodeXMLRequest(c context.Context, r *http.Request, request interface{}) error

EncodeXMLRequest is an EncodeRequestFunc that serializes the request as a XML object to the Request body. If the request implements Headerer, the provided headers will be applied to the request.

func PopulateRequestContext

func PopulateRequestContext(ctx context.Context, r *http.Request) context.Context

PopulateRequestContext is a RequestFunc that populates several values into the context from the HTTP request. Those values may be extracted using the corresponding ContextKey type in this package.

Example

Code:

handler := NewServer(
    func(ctx context.Context, request interface{}) (response interface{}, err error) {
        fmt.Println("Method", ctx.Value(ContextKeyRequestMethod).(string))
        fmt.Println("RequestPath", ctx.Value(ContextKeyRequestPath).(string))
        fmt.Println("RequestURI", ctx.Value(ContextKeyRequestURI).(string))
        fmt.Println("X-Request-ID", ctx.Value(ContextKeyRequestXRequestID).(string))
        return struct{}{}, nil
    },
    func(context.Context, *http.Request) (interface{}, error) { return struct{}{}, nil },
    func(context.Context, http.ResponseWriter, interface{}) error { return nil },
    ServerBefore(PopulateRequestContext),
)

server := httptest.NewServer(handler)
defer server.Close()

req, _ := http.NewRequest("PATCH", fmt.Sprintf("%s/search?q=sympatico", server.URL), nil)
req.Header.Set("X-Request-Id", "a1b2c3d4e5")
http.DefaultClient.Do(req)

Output:

Method PATCH
RequestPath /search
RequestURI /search?q=sympatico
X-Request-ID a1b2c3d4e5

type Client

Client wraps a URL and provides a method that implements endpoint.Endpoint.

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

func NewClient

func NewClient(
    method string,
    tgt *url.URL,
    enc EncodeRequestFunc,
    dec DecodeResponseFunc,
    options ...ClientOption,
) *Client

NewClient constructs a usable Client for a single remote method.

func (Client) Endpoint

func (c Client) Endpoint() endpoint.Endpoint

Endpoint returns a usable endpoint that invokes the remote endpoint.

type ClientOption

ClientOption sets an optional parameter for clients.

type ClientOption func(*Client)

func BufferedStream

func BufferedStream(buffered bool) ClientOption

BufferedStream sets whether the Response.Body is left open, allowing it to be read from later. Useful for transporting a file as a buffered stream.

func ClientAfter

func ClientAfter(after ...ClientResponseFunc) ClientOption

ClientAfter sets the ClientResponseFuncs applied to the incoming HTTP request prior to it being decoded. This is useful for obtaining anything off of the response and adding onto the context prior to decoding.

func ClientBefore

func ClientBefore(before ...RequestFunc) ClientOption

ClientBefore sets the RequestFuncs that are applied to the outgoing HTTP request before it's invoked.

func SetClient

func SetClient(client *http.Client) ClientOption

SetClient sets the underlying HTTP client used for requests. By default, http.DefaultClient is used.

type ClientResponseFunc

ClientResponseFunc may take information from an HTTP request and make the response available for consumption. ClientResponseFuncs are only executed in clients, after a request has been made, but prior to it being decoded.

type ClientResponseFunc func(context.Context, *http.Response) context.Context

type DecodeRequestFunc

DecodeRequestFunc extracts a user-domain request object from an HTTP request object. It's designed to be used in HTTP servers, for server-side endpoints. One straightforward DecodeRequestFunc could be something that JSON decodes from the request body to the concrete response type.

type DecodeRequestFunc func(context.Context, *http.Request) (request interface{}, err error)

type DecodeResponseFunc

DecodeResponseFunc extracts a user-domain response object from an HTTP response object. It's designed to be used in HTTP clients, for client-side endpoints. One straightforward DecodeResponseFunc could be something that JSON decodes from the response body to the concrete response type.

type DecodeResponseFunc func(context.Context, *http.Response) (response interface{}, err error)

type EncodeRequestFunc

EncodeRequestFunc encodes the passed request object into the HTTP request object. It's designed to be used in HTTP clients, for client-side endpoints. One straightforward EncodeRequestFunc could something that JSON encodes the object directly to the request body.

type EncodeRequestFunc func(context.Context, *http.Request, interface{}) error

type EncodeResponseFunc

EncodeResponseFunc encodes the passed response object to the HTTP response writer. It's designed to be used in HTTP servers, for server-side endpoints. One straightforward EncodeResponseFunc could be something that JSON encodes the object directly to the response body.

type EncodeResponseFunc func(context.Context, http.ResponseWriter, interface{}) error

type ErrorEncoder

ErrorEncoder is responsible for encoding an error to the ResponseWriter. Users are encouraged to use custom ErrorEncoders to encode HTTP errors to their clients, and will likely want to pass and check for their own error types. See the example shipping/handling service.

type ErrorEncoder func(ctx context.Context, err error, w http.ResponseWriter)

type Headerer

Headerer is checked by DefaultErrorEncoder. If an error value implements Headerer, the provided headers will be applied to the response writer, after the Content-Type is set.

type Headerer interface {
    Headers() http.Header
}

type RequestFunc

RequestFunc may take information from an HTTP request and put it into a request context. In Servers, RequestFuncs are executed prior to invoking the endpoint. In Clients, RequestFuncs are executed after creating the request but prior to invoking the HTTP client.

type RequestFunc func(context.Context, *http.Request) context.Context

func SetRequestHeader

func SetRequestHeader(key, val string) RequestFunc

SetRequestHeader returns a RequestFunc that sets the given header.

type Server

Server wraps an endpoint and implements http.Handler.

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

func NewServer

func NewServer(
    e endpoint.Endpoint,
    dec DecodeRequestFunc,
    enc EncodeResponseFunc,
    options ...ServerOption,
) *Server

NewServer constructs a new server, which implements http.Server and wraps the provided endpoint.

func (Server) ServeHTTP

func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler.

type ServerFinalizerFunc

ServerFinalizerFunc can be used to perform work at the end of an HTTP request, after the response has been written to the client. The principal intended use is for request logging. In addition to the response code provided in the function signature, additional response parameters are provided in the context under keys with the ContextKeyResponse prefix.

type ServerFinalizerFunc func(ctx context.Context, code int, r *http.Request)

type ServerOption

ServerOption sets an optional parameter for servers.

type ServerOption func(*Server)

func ServerAfter

func ServerAfter(after ...ServerResponseFunc) ServerOption

ServerAfter functions are executed on the HTTP response writer after the endpoint is invoked, but before anything is written to the client.

func ServerBefore

func ServerBefore(before ...RequestFunc) ServerOption

ServerBefore functions are executed on the HTTP request object before the request is decoded.

func ServerErrorEncoder

func ServerErrorEncoder(ee ErrorEncoder) ServerOption

ServerErrorEncoder is used to encode errors to the http.ResponseWriter whenever they're encountered in the processing of a request. Clients can use this to provide custom error formatting and response codes. By default, errors will be written with the DefaultErrorEncoder.

func ServerErrorLogger

func ServerErrorLogger(logger log.Logger) ServerOption

ServerErrorLogger is used to log non-terminal errors. By default, no errors are logged. This is intended as a diagnostic measure. Finer-grained control of error handling, including logging in more detail, should be performed in a custom ServerErrorEncoder or ServerFinalizer, both of which have access to the context.

func ServerFinalizer

func ServerFinalizer(f ServerFinalizerFunc) ServerOption

ServerFinalizer is executed at the end of every HTTP request. By default, no finalizer is registered.

type ServerResponseFunc

ServerResponseFunc may take information from a request context and use it to manipulate a ResponseWriter. ServerResponseFuncs are only executed in servers, after invoking the endpoint but prior to writing a response.

type ServerResponseFunc func(context.Context, http.ResponseWriter) context.Context

func SetContentType

func SetContentType(contentType string) ServerResponseFunc

SetContentType returns a ServerResponseFunc that sets the Content-Type header to the provided value.

func SetResponseHeader

func SetResponseHeader(key, val string) ServerResponseFunc

SetResponseHeader returns a ServerResponseFunc that sets the given header.

type StatusCoder

StatusCoder is checked by DefaultErrorEncoder. If an error value implements StatusCoder, the StatusCode will be used when encoding the error. By default, StatusInternalServerError (500) is used.

type StatusCoder interface {
    StatusCode() int
}