cliware

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2018 License: MIT Imports: 5 Imported by: 3 modules, 10 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

cliware

Go Report Card Build Status codecov status GoDoc

Cliware - middlewares from clients.

Cliware is library that defines concept of middlewares for HTTP clients. In Go community, middlewares are known concept for server side development. They are widely used and there are a lot of useful middleware implementations around.

When it comes to implementing HTTP client, there is no standard. There are some great libraries, but there is no real plug-and-play mechanism as there is for common server handlers. Idea behind this library is to make it possible for others to write client middlewares and compose them to create HTTP clients.

Install

Run go get github.com/delicb/cliware in terminal.

Usage

Two main types in cliware are Handler and Middleware. They are both interfaces with some helper around them.

Handler

Handler defines Handle method whose job is to take request (with context already attached to it) which is instance of *http.Request and return *http.Response with potential error (just like http.Client.Do does).

Handler defines Handle method whose job is to take context in which it is being executed and instance of *http.Request and return *http.Response ( with optional error). That is it. It is pretty similar to what *http.Client.Do method does, except it does not accept context as first parameter.

At least one Handler has to exist and that is one that will send request over network. Most simple implementation would be just using http.Client.Do method. If additional work has to be done, something like this should be implemented:

func finalHandler(req *http.Request) (resp *http.Response, err error) {
    // something before sending request
    resp, err := http.DefaultClient.Do(req.WithContext(ctx))
    // something after sending request
    return resp, err
}
Middleware

Middleware is interface that also defines only one method. That method is Exec and it accepts next Handler in to be called and returns new Handler.

Middlewares can wrap handlers based on some parameters, do some stuff before and after next handler, modify request, inspect response, etc. Middleware HAS TO call next handler that was provided to Exec or else entire chain will stop executing.

HandlerFunc

HandlerFunc is a function type that has same signature as Handle method from Handler interface. You can see it as utility that will convert your function with proper signature into Handler implementation.

MiddlewareFunc

MiddlewareFunc is same principle from HandlerFunc, just applied to Middleware.

RequestProcessor

RequestProcessor is function type that implements Middleware interface. It is not special type of Middleware, but just convenience for middlewares that only need to do something with request and do not care about response. This allows for such middlewares to have less verbose signature and it automatically calls next handler.

ResponseProcessor

ResponseProcessor is same principle as RequestProcessor, just applied to responses. So, if middleware only needs to inspect response you can use this convenience function.

ContextProcessor

ContextProcessor is same principle as RequestProcessor and ResponseProcessor but applied only to context.Context that is passed as first parameter to each handler. It can be used if middleware only needs to modify context (like setting timeout or deadline) to context.

Chain

Chain is special kind of Middleware. Instead of wrapping one Handler with another, Chain can hold multiple middlewares that will all be applied in sequence, thus effectively wrapping final Handler.

That is all chain does (plus some additional utility methods for adding other middlewares to the chain).

Scope

Scope of this library is pretty small. It only defines required types (for handler and middleware) and mechanism how they are chained. That is it. No useful middlewares (I am writing library of them, still work in progress but check out cliware-middlewares), No http client implementation (also writing one, check out GWC).

Dependencies

No dependencies beyond GoLang standard library.

Currently, cliware requires GoLang 1.7 to work, but I will not constrain from using new language features and new versions of GoLang come out. Therefor, make sure to vendor this library if you intend to use it in production.

Contributing

Most appreciated contributions would be written middlewares that use Cliware. If you do write some, please ping me to add link to this description.

Of course, feel free to open tickets (or even better, pull requests). I am opened to suggestions.

Name

Very creatively, name is combination of words CLI(ent) and (Middle)WARE.

Examples

There are (testable) examples in repository itself. Just checkout files whose name starts with example_

Licence

Cliware is released under MIT licence.

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

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func EmptyRequest

func EmptyRequest() *http.Request

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) Copy

func (c *Chain) Copy() *Chain

Copy creates new chain with all middlewares copied to it.

func (*Chain) Exec

func (c *Chain) Exec(handler Handler) Handler

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) UseFunc

func (c *Chain) UseFunc(m func(handler Handler) Handler)

UseFunc adds provided function to current middleware chain.

func (*Chain) UseRequest

func (c *Chain) UseRequest(m func(req *http.Request) error)

UseRequest adds provided function as request middleware.

func (*Chain) UseResponse

func (c *Chain) UseResponse(m func(resp *http.Response, err error) error)

UseResponse add provided function as response middleware.

type ContextProcessor

type ContextProcessor func(ctx context.Context) context.Context

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

type HandlerFunc func(req *http.Request) (resp *http.Response, err error)

HandlerFunc is function variant of RequestHandler interface.

func (HandlerFunc) Handle

func (rhf HandlerFunc) Handle(req *http.Request) (resp *http.Response, err error)

Handle is implementation 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

type MiddlewareFunc func(handler Handler) Handler

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

type RequestProcessor func(req *http.Request) error

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

type ResponseProcessor func(resp *http.Response, err error) error

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)
}

func (ResponseProcessor) Exec

func (rp ResponseProcessor) Exec(handler Handler) Handler

Exec is implementation of Middleware interface.

Jump to

Keyboard shortcuts

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