Documentation ¶
Overview ¶
Package libhttp is the new kid on the block. Watch out.
Index ¶
- Constants
- func ErrorStatusCode(err error) int
- func HSTSFilter(maxAge int) func(request Request, service Service) Response
- func HttpHandler(svc Service) http.Handler
- func Streamer() io.ReadWriteCloser
- type Filter
- type Request
- func (r *Request) BodyBytes(consume bool) ([]byte, error)
- func (r Request) Decode(v interface{}) error
- func (r *Request) Encode(v interface{})
- func (r Request) Response(body interface{}) Response
- func (r Request) Send() *ResponseFuture
- func (r Request) SendVia(svc Service) *ResponseFuture
- func (r Request) String() string
- func (r *Request) Write(b []byte) (n int, err error)
- type Response
- type ResponseFuture
- type ResponseWriter
- type Router
- func (r *Router) CONNECT(pattern string, svc Service)
- func (r *Router) DELETE(pattern string, svc Service)
- func (r *Router) GET(pattern string, svc Service)
- func (r *Router) HEAD(pattern string, svc Service)
- func (r Router) Lookup(method, path string) (Service, string, map[string]string, bool)
- func (r *Router) OPTIONS(pattern string, svc Service)
- func (r *Router) PATCH(pattern string, svc Service)
- func (r *Router) POST(pattern string, svc Service)
- func (r *Router) PUT(pattern string, svc Service)
- func (r Router) Params(req Request) map[string]string
- func (r Router) Pattern(req Request) string
- func (r *Router) Register(method, pattern string, svc Service)
- func (r Router) Serve() Service
- func (r *Router) TRACE(pattern string, svc Service)
- type Server
- func Listen(svc Service, addr string) (*Server, error)
- func ListenTLS(svc Service, addr, certFile, keyFile string, cfg *tls.Config) (*Server, error)
- func ListenUnix(svc Service, path string) (*Server, error, func())
- func ListenUnixTLS(svc Service, path, certFile, keyFile string, cfg *tls.Config) (*Server, error, func())
- func Serve(svc Service, l net.Listener) (*Server, error)
- func ServeTLS(svc Service, l net.Listener, certFile, keyFile string, cfg *tls.Config) (*Server, error)
- type Service
- type WrapDownstreamErrors
Constants ¶
const (
HSTSDefaultMaxAge = 63072000
)
Variables ¶
This section is empty.
Functions ¶
func ErrorStatusCode ¶
ErrorStatusCode returns a HTTP status code for the given error.
If the error is not a terror, this will always be 500 (Internal Server Error).
func HttpHandler ¶
HttpHandler transforms the given Service into a standard library HTTP handler. It is one of the main "bridges" between Typhon and net/http.
func Streamer ¶
func Streamer() io.ReadWriteCloser
Streamer returns a reader/writer/closer that can be used to stream responses. A simple use of this is:
func streamingService(req libhttp.Request) libhttp.Response { body := libhttp.Streamer() go func() { defer body.Close() // do something to asynchronously produce output into body }() return req.Response(body) }
Note that a Streamer may not perform any internal buffering, so callers should take care not to depend on writes being non-blocking. If buffering is needed, Streamer can be wrapped in a bufio.Writer.
Types ¶
type Filter ¶
Filter functions compose with Services to modify their behaviour. They might change a service's input or output, or elect not to call the underlying service at all.
These are typically useful to encapsulate common logic that is shared among multiple Services. Authentication, authorisation, rate limiting, and tracing are good examples.
type Request ¶
A Request is Typhon's wrapper around http.Request, used by both clients and servers.
Note that Typhon makes no guarantees that a Request is safe to access or mutate concurrently. If a single Request object is to be used by multiple goroutines concurrently, callers must make sure to properly synchronise accesses.
func NewRequest ¶
NewRequest constructs a new Request with the given parameters, and if non-nil, encodes the given body into it.
func (*Request) BodyBytes ¶
BodyBytes fully reads the request body and returns the bytes read.
If consume is true, this is equivalent to ioutil.ReadAll; if false, the caller will observe the body to be in the same state that it was before (ie. any remaining unread body can be read again).
func (*Request) Encode ¶
func (r *Request) Encode(v interface{})
Encode serialises the passed object as JSON into the body (and sets appropriate headers).
func (Request) Response ¶
Response construct a new Response to the request, and if non-nil, encodes the given body into it.
func (Request) Send ¶
func (r Request) Send() *ResponseFuture
Send round-trips the request via the default Client. It does not block, instead returning a ResponseFuture representing the asynchronous operation to produce the response. It is equivalent to:
r.SendVia(Client)
func (Request) SendVia ¶
func (r Request) SendVia(svc Service) *ResponseFuture
SendVia round-trips the request via the passed Service. It does not block, instead returning a ResponseFuture representing the asynchronous operation to produce the response.
type Response ¶
type Response struct { *http.Response Error error Request *Request // The Request that we are responding to // contains filtered or unexported fields }
A Response is Typhon's wrapper around http.Response, used by both clients and servers.
Note that Typhon makes no guarantees that a Response is safe to access or mutate concurrently. If a single Response object is to be used by multiple goroutines concurrently, callers must make sure to properly synchronise accesses.
func BareClient ¶
BareClient is the most basic way to send a request, using the default http RoundTripper
func ErrorFilter ¶
ErrorFilter serialises and deserialises response errors. Without this filter, errors may not be passed across the network properly so it is recommended to use this in most/all cases.
func ExpirationFilter ¶
ExpirationFilter provides admission control; it rejects requests which are cancelled
func H2cFilter ¶
H2cFilter adds HTTP/2 h2c upgrade support to the wrapped Service (as defined in RFC 7540 §3.2, §3.4).
func (*Response) BodyBytes ¶
BodyBytes fully reads the response body and returns the bytes read. If consume is false, the body is copied into a new buffer such that it may be read again.
func (*Response) Encode ¶
func (r *Response) Encode(v interface{})
Encode serialises the passed object as JSON into the body (and sets appropriate headers).
func (*Response) Writer ¶
func (r *Response) Writer() ResponseWriter
Writer returns a ResponseWriter which can be used to populate the response.
This is useful when you want to use another HTTP library that is used to wrapping net/http directly. For example, it allows a Typhon Service to use a http.Handler internally.
type ResponseFuture ¶
type ResponseFuture struct {
// contains filtered or unexported fields
}
A ResponseFuture is a container for a Response which will materialise at some point.
func Send ¶
func Send(req Request) *ResponseFuture
Send round-trips the request via the default Client. It does not block, instead returning a ResponseFuture representing the asynchronous operation to produce the response. It is equivalent to:
SendVia(req, Client)
func SendVia ¶
func SendVia(req Request, svc Service) *ResponseFuture
SendVia round-trips the request via the passed Service. It does not block, instead returning a ResponseFuture representing the asynchronous operation to produce the response.
func (*ResponseFuture) Response ¶
func (f *ResponseFuture) Response() Response
Response provides access to the response object, blocking until it is available
func (*ResponseFuture) WaitC ¶
func (f *ResponseFuture) WaitC() <-chan struct{}
WaitC returns a channel which can be waited upon until the response is available
type ResponseWriter ¶
type ResponseWriter interface { http.ResponseWriter // WriteJSON writes the given data as JSON to the Response. The passed value must (perhaps obviously) be // serialisable to JSON. WriteJSON(interface{}) // WriteError writes the given error to the Response. WriteError(err error) }
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
A Router multiplexes requests to a set of Services by pattern matching on method and path, and can also extract parameters from paths.
func RouterForRequest ¶
RouterForRequest returns a pointer to the Router that successfully dispatched the request, or nil.
func (Router) Lookup ¶
Lookup returns the Service, pattern, and extracted path parameters for the HTTP method and path.
func (Router) Params ¶
Params returns extracted path parameters, assuming the request has been routed and has captured parameters.
func (*Router) Register ¶
Register associates a Service with a method and path.
Method is a HTTP method name, or "*" to match any method.
Patterns are strings of the format: /foo/:name/baz/*residual As well as being literal paths, they can contain named parameters like :name whose value is dynamic and only known at runtime, or *residual components which match (potentially) multiple path components.
In the case that patterns are ambiguous, the last route to be registered will take precedence.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
func ListenUnix ¶ added in v1.2.0
func ListenUnixTLS ¶ added in v1.2.0
func ServeTLS ¶
func ServeTLS(svc Service, l net.Listener, certFile, keyFile string, cfg *tls.Config) (*Server, error)
Serve starts a HTTPS server, binding the passed Service to the passed listener.
func (*Server) Done ¶
func (s *Server) Done() <-chan struct{}
Done returns a channel that will be closed when the server begins to shutdown. The server may still be draining its connections at the time the channel is closed.
type Service ¶
A Service is a function that takes a request and produces a response. Services are used symmetrically in both clients and servers.
var ( // Client is used to send all requests by default. It can be overridden globally but MUST only be done before use // takes place; access is not synchronised. Client Service = BareClient // RoundTripper is used by default in Typhon clients RoundTripper http.RoundTripper = &http.Transport{ Proxy: http.ProxyFromEnvironment, DisableKeepAlives: false, DisableCompression: false, IdleConnTimeout: 10 * time.Minute, MaxIdleConnsPerHost: 10} )
func FromHTTPHandler ¶ added in v1.3.0
FromHTTPHandler turns your legacy http handlers into a libhttp Service
func HttpService ¶
func HttpService(rt http.RoundTripper) Service
HttpService returns a Service which sends requests via the given net/http RoundTripper. Only use this if you need to do something custom at the transport level.
type WrapDownstreamErrors ¶
type WrapDownstreamErrors struct{}
WrapDownstreamErrors is a context key that can be used to enable wrapping of downstream response errors on a per-request basis.
This is implemented as a context key to allow us to migrate individual services from the old behaviour to the new behaviour without adding a dependency on config to Typhon.