Documentation
¶
Overview ¶
Package cliware defines base type for HTTP client middleware support.
Cliware does very little on its own. Main purpose is for other packages to implement useful HTTP client middlewares and to write clients using cliware and set of useful middlewares. That being said, cliware can be used on its own with GoLang standard library.
Just as net/http package defines Handler interface that is used to write HTTP server handlers and compose them, this package defines similar concept but for HTTP client. net/http.Handler interface enabled a lot of third party middlewares to be written that are very useful. This package has the same idea. It provides type definition and some useful helper stuff around it (like ability to chain middlewares) in hope that other developer will catch up and write useful middlewares for everyone to use.
Example ¶
package main
import (
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"net/url"
"os"
c "github.com/delicb/cliware"
)
var server *httptest.Server
// startServer starts dummy example server that will be used to demonstrate
// how middlewares work.
func startServer() {
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// print some headers
fmt.Println("User-Agent: ", r.Header.Get("User-Agent"))
fmt.Println("Custom-Header: ", r.Header.Get("X-Custom-Header"))
// dump body to stdout
_, err := io.Copy(os.Stdout, r.Body)
if err != nil {
panic(err)
}
defer func() {
err := r.Body.Close()
if err != nil {
panic(err)
}
}()
// return some response
w.WriteHeader(200)
_, err = w.Write([]byte("My shiny server response"))
if err != nil {
panic(err)
}
}))
}
// stopServer stops testing server
func stopServer() {
server.Close()
}
// serverURL sets request URL to match URL of provided test server.
// This is example of middleware that modifies request before sending it.
// It uses utility function RequestProcessor.
func serverURL(server *httptest.Server) c.Middleware {
return c.RequestProcessor(func(r *http.Request) error {
u, err := url.Parse(server.URL)
if err != nil {
return err
}
r.URL = u
return nil
})
}
// header adds header with provided name and value to request.
// This is another example of middleware that modifies request before sending
// it.
func header(name, value string) c.Middleware {
return c.RequestProcessor(func(r *http.Request) error {
r.Header.Set(name, value)
return nil
})
}
// bodyToStdout reads response body and copies it to standard output.
// This is example of middleware that inspects response and does something
// with returned body.
func bodyToStdout() c.Middleware {
return c.ResponseProcessor(func(resp *http.Response, err error) error {
if err != nil {
log.Println("Got error:", err)
return err
}
defer func() {
err := resp.Body.Close()
if err != nil {
panic(err)
}
}()
fmt.Println()
fmt.Println("Got response:")
_, err = io.Copy(os.Stdout, resp.Body)
return err
})
}
// trace writes something to standard output before and after request has been sent.
// This is example of middleware without utility functions that does something
// both before and after request has been sent.
func trace(next c.Handler) c.Handler {
return c.HandlerFunc(func(req *http.Request) (resp *http.Response, err error) {
// do anything before request
fmt.Println("*** Before sending request.")
// call next middleware
resp, err = next.Handle(req)
// do anything after request
fmt.Println("*** After sending request.")
// return result
return resp, err
})
}
// sender does actual request sending using htt.Client.
// this is final handler that has to be called and it has to be passed to
// chain Exec method.
func sender(req *http.Request) (resp *http.Response, err error) {
return http.DefaultClient.Do(req)
}
func main() {
startServer()
defer stopServer()
// middlewares will be applied in order defined here
chain := c.NewChain(
serverURL(server),
header("User-Agent", "Cliware"),
header("X-Custom-Header", "whatever"),
bodyToStdout(),
)
// other way to add middlewares is by using Use* method
chain.UseFunc(trace)
// execute chain and final middleware
_, err := chain.Exec(c.HandlerFunc(sender)).Handle(c.EmptyRequest())
if err != nil {
panic(err)
}
}
Output: *** Before sending request. User-Agent: Cliware Custom-Header: whatever *** After sending request. Got response: My shiny server response
Index ¶
- func EmptyRequest() *http.Request
- type Chain
- func (c *Chain) ChildChain(middlewares ...Middleware) *Chain
- func (c *Chain) Copy() *Chain
- func (c *Chain) Exec(handler Handler) Handler
- func (c *Chain) Middlewares() []Middleware
- func (c *Chain) Parent() Middleware
- func (c *Chain) Use(m ...Middleware)
- func (c *Chain) UseFunc(m func(handler Handler) Handler)
- func (c *Chain) UseRequest(m func(req *http.Request) error)
- func (c *Chain) UseResponse(m func(resp *http.Response, err error) error)
- type ContextProcessor
- type Handler
- type HandlerFunc
- type Middleware
- type MiddlewareFunc
- type RequestProcessor
- type ResponseProcessor
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func EmptyRequest ¶
EmptyRequest creates new empty instance of *http.Request. It is good starting point for initial request instance for middleware chain. In contrast to http.NewRequest, this function does not require any parameters. Any value can be overridden by middlewares. Request method is set to GET, just because it is sane default.
Types ¶
type Chain ¶
type Chain struct {
// contains filtered or unexported fields
}
Chain is Middleware implementation capable of executing multiple middlewares. On top of that, chain is aware of its parent middleware and executes it during its own execution.
func NewChain ¶
func NewChain(middlewares ...Middleware) *Chain
NewChain creates and returns middleware chain with provided middlewares and no parent. If you need to create new chain with some parent, use ChildChain method.
func (*Chain) ChildChain ¶
func (c *Chain) ChildChain(middlewares ...Middleware) *Chain
ChildChain creates new Middleware chain with current chain as parent.
func (*Chain) Exec ¶
Exec is implementation of Middleware interface that executes all middlewares in chain, including parent middleware.
func (*Chain) Middlewares ¶
func (c *Chain) Middlewares() []Middleware
Middlewares returns all middlewares for this chain. Parent middlewares not included.
func (*Chain) Parent ¶
func (c *Chain) Parent() Middleware
Parent returns parent middleware of this chain.
func (*Chain) Use ¶
func (c *Chain) Use(m ...Middleware)
Use adds provided middleware to current middleware chain.
func (*Chain) UseRequest ¶
UseRequest adds provided function as request middleware.
type ContextProcessor ¶
ContextProcessor is function for managing request context. It is intended as form of simple middleware for middlewares that only need to modify context before sending request.
func (ContextProcessor) Exec ¶
func (cp ContextProcessor) Exec(handler Handler) Handler
Exec is implementation of Middleware interface.
type Handler ¶
type Handler interface {
// Handle executes HTTP request based on provided parameters.
// Depending on implementation, provided context might or not be used.
// However, if handler really performs HTTP request (as opposed to doing
// some middleware work, like logging or similar), provided context SHOULD
// be used on request as intended by http.Request.WithRequest method.
Handle(req *http.Request) (resp *http.Response, err error)
}
Handler is interface that defines processing HTTP client request.
type HandlerFunc ¶
HandlerFunc is function variant of RequestHandler interface.
type Middleware ¶
type Middleware interface {
// Exec returns Handler that does some useful work. Implementation SHOULD
// call provided next Handler somewhere in returned Handler to ensure chain
// is not broken. However, implementation might choose not to call next
// handler based on external influence, error checking, etc. In that case,
// returned Handler MUST return error.
Exec(next Handler) Handler
}
Middleware defines interface for chaining Handlers.
type MiddlewareFunc ¶
MiddlewareFunc is function variant of Middleware interface.
func (MiddlewareFunc) Exec ¶
func (mf MiddlewareFunc) Exec(handler Handler) Handler
Exec is implementation of Middleware interface.
type RequestProcessor ¶
RequestProcessor is function for modification of HTTP request. It is intended as form of simple Middleware for middlewares that only need to change request that is being sent. Provided request can be modified as required. Returned error (if any) will stop middleware chain execution and same error will be returned to caller.
Example ¶
package main
import (
"fmt"
"net/http"
c "github.com/delicb/cliware"
)
// basicAuth is simple middleware that modifies request by adding basic authentication
// to it.
func basicAuth(username, password string) c.Middleware {
return c.RequestProcessor(func(req *http.Request) error {
req.SetBasicAuth(username, password)
return nil
})
}
func nilHandler(req *http.Request) (*http.Response, error) {
return nil, nil
}
func main() {
req := c.EmptyRequest()
_, err := basicAuth("user", "pass").Exec(c.HandlerFunc(nilHandler)).Handle(req)
if err != nil {
panic(err)
}
username, password, ok := req.BasicAuth()
fmt.Println(ok)
fmt.Println(username)
fmt.Println(password)
}
Output: true user pass
func (RequestProcessor) Exec ¶
func (rp RequestProcessor) Exec(handler Handler) Handler
Exec is implementation of Middleware interface.
type ResponseProcessor ¶
ResponseProcessor is function for inspection of HTTP response. It is intended as form of a simple Middleware for middlewares that only need to inspect responses. E.g. they can log some information or inspect response to determine if error occurred. Provided response if one obtained from sending HTTP request and should not be modified. Provided error is original error returned after request or error returned by previous middleware. If middleware wants to change error - it should return it. Otherwise, if there is not error or existing (provided) error should not be changed, middleware should return nil.
Example ¶
package main
import (
"fmt"
"net/http"
"net/url"
c "github.com/delicb/cliware"
)
// HTTPError is struct holding information about HTTP response that went wrong.
type HTTPError struct {
Status string
StatusCode int
URL string
Method string
}
// Error is implementation of error interface for HTTPError.
func (h *HTTPError) Error() string {
return fmt.Sprintf("%s %s (%d %s)", h.Method, h.URL, h.StatusCode, h.Status)
}
// statusCodeToError is middleware that inspects HTTP response and if its
// response code is higher or equal to 400 creates HTTPError instance and
// passes it down the chain with response relevant response information.
func statusCodeToError() c.Middleware {
return c.ResponseProcessor(func(resp *http.Response, err error) error {
// no further processing if we already got error, but in different
// middleware we can inspect error, replace it or suppress it
if err != nil {
return err
}
if resp.StatusCode >= 400 {
return &HTTPError{
Status: resp.Status,
StatusCode: resp.StatusCode,
URL: resp.Request.URL.String(),
Method: resp.Request.Method,
}
}
return nil
})
}
// notFoundResponse is helper method that always returns HTTP response with
// 404 Not Found status.
func notFoundResponse(req *http.Request) (*http.Response, error) {
return &http.Response{
Status: http.StatusText(http.StatusNotFound),
StatusCode: http.StatusNotFound,
Request: &http.Request{
URL: &url.URL{
Path: "/some_path",
},
Method: "GET",
},
}, nil
}
func main() {
_, err := statusCodeToError().Exec(c.HandlerFunc(notFoundResponse)).Handle(nil)
fmt.Println(err)
}
Output:
func (ResponseProcessor) Exec ¶
func (rp ResponseProcessor) Exec(handler Handler) Handler
Exec is implementation of Middleware interface.