gwc

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2018 License: MIT Imports: 14 Imported by: ? modules, 0 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

GWC (Go Web Client)

Go Report Card Build Status codecov status GoDoc

GWC is GoLang HTTP client based on Cliware client middleware management library and its middlewares.

Basic idea is to use same middleware mechanism on client side as many projects use it for server development.

Because it is based on middlewares client is very pluggable. However, even out of box it should support most common use cases.

Install

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

Example

There is testable example in this repository. It basically does following:

package gwc

import (
	"fmt"
	"net/http"

    "github.com/delicb/gwc"
	"github.com/delicb/cliware-middlewares/headers"
	"github.com/delicb/cliware-middlewares/errors"
)

type HTTPBinResponse struct {
	Headers struct {
		UserAgent string `json:"User-Agent"`
	} `json:"headers"`
}

func main() {
	respBody := new(HTTPBinResponse)

	client := gwc.New(
		http.DefaultClient,
		// Add user agent header, it will be applied to all requests
		headers.Add("User-Agent", "example-client"),
		errors.Errors(),
	)
	// send request
	resp, err := client.Get().URL("https://httpbin.org/get").Send()
	
	// check errors
	// because of errors middleware included in client, ever status codes 
	// 400+ will be turned into errors.
	if err != nil {
		panic(err)
	}

	resp.JSON(respBody)
	fmt.Println(respBody.Headers.UserAgent)
	// output: example-client
}

In this example we create new GWC instance with some middlewares (in this case we set User-Agent header to each request sent using this middleware).

We use client to send request and (after some error checking) we deserialize JSON body to structure.

State

This is early development, not stable, backward compatibility not guarantied.

Currently, GWC requires GoLang 1.7 to work. However, in the future I will not hesitate from using new language features. Therefor, make sure to vendor this library if you intend to use it.

Contribution

Any contribution is welcome. If you find this code useful, please let me know. If you find bugs - feel free to open an issue, or, even better, new pull request.

Credits

Idea and bunch of implementation details were taken from cool GoLang HTTP client Gentleman.

Difference is that GWC is based on Cliware, which supports context for client requests and has more simple idea of middleware. Also, GWC is lacking some features that Gentleman has (like mux). For now I do not plan on adding them to GWC, but I might write middleware that support similar functionality in the future.

Documentation

Overview

Package gwc is simple HTTP client based on premise to use client side middlewares. It is based on cliware library that defines basic type for client side middlewares and series of middlewares implemented in cliware-middlewares package.

Basic idea behind this client is to create simple, yet easily composable HTTP client. Client does provide simple Request and Response types, but they are only thin wrappers around same type in http package used for middleware composition.

Example
package main

import (
	"fmt"
	"net/http"

	"github.com/delicb/cliware-middlewares/errors"
	"github.com/delicb/cliware-middlewares/headers"
)

type HTTPBinResponse struct {
	Headers struct {
		UserAgent string `json:"User-Agent"`
	} `json:"headers"`
}

func main() {
	respBody := new(HTTPBinResponse)

	client := New(
		http.DefaultClient,
		// Add user agent header, it will be applied to all requests
		headers.Add("User-Agent", "example-client"),
		errors.Errors(),
	)
	// send request
	resp, err := client.Get().URL("https://httpbin.org/get").Send()

	// check errors
	// because of errors middleware included in client, ever status codes
	// 400+ will be turned into errors.
	if err != nil {
		panic(err)
	}

	resp.JSON(respBody)
	fmt.Println(respBody.Headers.UserAgent)
}
Output:
example-client

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ClientFromContext

func ClientFromContext(ctx context.Context) *http.Client

ClientFromContext returns client instance from context. If client is not set, nil will be returned.

Types

type Client

type Client struct {
	Before *cliware.Chain
	After  *cliware.Chain
	// contains filtered or unexported fields
}

Client is main point of contact with this this library. It is used to set up basic configuration that will be used for all requests (except if it is overridden on per-request basis). For better performance (reuse of connections) only one instance of client should be created.

func New

func New(client *http.Client, middlewares ...cliware.Middleware) *Client

New creates and returns instance of a client. First parameter is http.Client instance that will be used to send actual requests. This can be used to modify default behavior (like TLS or timeouts). If nil is provided, &http.Client{} will be used.

Also, any number of middlewares can be provided. These will be used for each request. Additional middlewares can be added by using "Use*" methods on a client.

func (*Client) Delete

func (c *Client) Delete() *Request

Delete creates and returns new DELETE request.

func (*Client) Do

func (c *Client) Do(middlewares ...cliware.Middleware) (*Response, error)

Do creates new request, applies all provided middlewares to it and sends request. Context that is used is context.Background()

func (*Client) DoCtx

func (c *Client) DoCtx(ctx context.Context, middlewares ...cliware.Middleware) (*Response, error)

DoCtx creates new request, applies all provided middlewares to it and sends request with provided context.

func (*Client) Get

func (c *Client) Get() *Request

Get creates and returns new GET request.

func (*Client) Head

func (c *Client) Head() *Request

Head creates and returns new HEAD request.

func (*Client) Options

func (c *Client) Options() *Request

Options creates and returns new OPTIONS request.

func (*Client) Patch

func (c *Client) Patch() *Request

Patch creates and returns new PATCH request.

func (*Client) Post

func (c *Client) Post() *Request

Post creates and returns new POST request.

func (*Client) Put

func (c *Client) Put() *Request

Put creates and returns new PUT request.

func (*Client) Request

func (c *Client) Request() *Request

Request creates and returns new request that uses this client to perform HTTP request and uses its defined middlewares.

func (*Client) Use

func (c *Client) Use(m cliware.Middleware) *Client

Use adds provided middleware to this clients middleware chain.

func (*Client) UseFunc

func (c *Client) UseFunc(m func(cliware.Handler) cliware.Handler) *Client

UseFunc adds provided function to this clients middleware chain.

func (*Client) UsePost

func (c *Client) UsePost(m cliware.Middleware) *Client

UsePost adds middleware that will be added to all requests sent by this client AFTER middlewares from request itself are executed.

func (*Client) UsePostFunc

func (c *Client) UsePostFunc(m func(cliware.Handler) cliware.Handler) *Client

UsePostFunc adds middleware that will be added to all requests sent by this client AFTER middlewares from request itself are executed.

type Doer

type Doer interface {
	Do(middlewares ...cliware.Middleware) (*Response, error)
	DoCtx(ctx context.Context, middlewares ...cliware.Middleware) (*Response, error)
}

Doer defines that object is capable of executing HTTP request with provided middlewares.

type Group

type Group struct {
	Next  Doer
	Chain *cliware.Chain
}

Group is container of any additional middlewares that group of endpoints use.

func NewGroup

func NewGroup(next Doer, middlewares ...cliware.Middleware) *Group

NewGroup creates and returns new instance of Group that will apply all provided middlewares and use next Doer to do actual work.

func (*Group) Do

func (s *Group) Do(middlewares ...cliware.Middleware) (*Response, error)

Do applies all middlewares from this layer and provided middlewares and calls next Doer to do actual work.

func (*Group) DoCtx

func (s *Group) DoCtx(ctx context.Context, middlewares ...cliware.Middleware) (*Response, error)

DoCtx applies all middlewares from this layer and provided middlewares and calls next Doer to do actual work.

func (*Group) Exec

func (s *Group) Exec(handler cliware.Handler) cliware.Handler

Exec is implementation of cliware.Middleware interface.

func (*Group) Use

func (s *Group) Use(middleware ...cliware.Middleware) *Group

Use adds provided middlewares to this group's chain.

type Request

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

Request is struct used to hold information (mostly middlewares) used to construct HTTP request.

func NewRequest

func NewRequest(client *Client, before *cliware.Chain, after *cliware.Chain) *Request

NewRequest creates new instance of request for provided client and with initial middleware chain.

func (*Request) AddCookie

func (r *Request) AddCookie(cookie *http.Cookie) *Request

AddCookie adds provided cookie to current request.

func (*Request) AddHeader

func (r *Request) AddHeader(key, value string) *Request

AddHeader adds header with provided name and value to current request. It does not override existing headers.

func (*Request) AddPath

func (r *Request) AddPath(path string) *Request

AddPath appends path segment to current path for this request.

func (*Request) AddQuery

func (r *Request) AddQuery(key, value string) *Request

AddQuery adds query parameter to URL for this request. If parameter with same name already exist, new one will be appended. To replace it, use SetQuery.

func (*Request) BaseURL

func (r *Request) BaseURL(rawURL string) *Request

BaseURL sets schema and host from provided URL to this request.

func (*Request) BodyJSON

func (r *Request) BodyJSON(data interface{}) *Request

BodyJSON adds provided data to request as JSON encoded body.

func (*Request) Context

func (r *Request) Context() context.Context

Context returns instance of context.Context used for this request.

func (*Request) Method

func (r *Request) Method(method string) *Request

Method sets HTTP method (verb) for this request.

func (*Request) Param

func (r *Request) Param(key, value string) *Request

Param replaces key in caramelized URL with given value for this request.

func (*Request) Params

func (r *Request) Params(values map[string]string) *Request

Params replaces all keys in URL with key-value pairs provided in map for this request.

func (*Request) Path

func (r *Request) Path(path string) *Request

Path sets path to URL for this request.

func (*Request) Send

func (r *Request) Send() (*Response, error)

Send constructs and sends HTTP request. This method uses all defined middlewares and client defined in requests to construct HTTP request.

func (*Request) SetContext

func (r *Request) SetContext(ctx context.Context) *Request

SetContext sets instance of context.Context used for this request.

func (*Request) SetCookie

func (r *Request) SetCookie(key, value string) *Request

SetCookie set cookie with provided name and value to current request.

func (*Request) SetHeader

func (r *Request) SetHeader(key, value string) *Request

SetHeader sets provided header value to current request. If header with same name already exists, it will be overridden. To add same header again, use AddHeader.

func (*Request) SetHeaders

func (r *Request) SetHeaders(headerMap map[string]string) *Request

SetHeaders sets headers for this request provided in map.

func (*Request) SetQuery

func (r *Request) SetQuery(key, value string) *Request

SetQuery sets query parameter to URL for this request. If parameter already exists it will be replaced.

func (*Request) SetQueryParams

func (r *Request) SetQueryParams(values map[string]string) *Request

SetQueryParams sets query parameters for this request provided in the map.

func (*Request) URL

func (r *Request) URL(rawURL string) *Request

URL parses and sets URL for this request.

func (*Request) Use

func (r *Request) Use(m ...cliware.Middleware) *Request

Use adds provided middleware to this request middleware chain.

func (*Request) UseFunc

func (r *Request) UseFunc(m func(cliware.Handler) cliware.Handler) *Request

UseFunc adds provided function to this request middleware chain.

type Response

type Response struct {
	*http.Response
	Error error
}

Response is thin wrapper around http.Response that provides some convenient behavior.

func BuildResponse

func BuildResponse(rawResponse *http.Response, err error) *Response

BuildResponse creates new instance of response based on provided raw HTTP response.

func (*Response) Bytes

func (r *Response) Bytes() ([]byte, error)

Bytes returns raw bytes read from response body.

func (*Response) JSON

func (r *Response) JSON(userStruct interface{}) error

JSON decodes response body to provided structure from JSON format.

func (*Response) SaveToFile

func (r *Response) SaveToFile(filename string) error

SaveToFile writes response content to file with provided path.

func (*Response) String

func (r *Response) String() (string, error)

String returns response body in string format.

func (*Response) XML

func (r *Response) XML(userStruct interface{}) error

XML decodes response body to provided structure from XML format.

Jump to

Keyboard shortcuts

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