httpsimplified

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 2018 License: MIT Imports: 11 Imported by: 0

README

httpsimplified

GoDoc

Package httpsimplified sends outgoing HTTP requests via a simple straightforward API distilled from many internal Golang projects at USA Today Network. It embraces Go stdlib types like url.Values and http.Header, provides composable building blocks for more complex use cases and doesn't try to be clever.

See godoc.org/github.com/andreyvit/httpsimplified for a full reference.

Call Get, Post or Put to send a request and parse the response in a single call:

var resp responseType
err := httpsimplified.Get(baseURL, path, params, headers, httpsimplified.JSON, &resp)

where httpsimplified.JSON is a body parser function (we also provide PlainText, Bytes, Raw and None parsers, and you can define your own). See the example for more details.

For more advanced requests, build http.Request yourself and call Perform:

var resp responseType
err := httpsimplified.Perform(&http.Request{
    Method: http.MethodPut,
    URL:    httpsimplified.URL(baseURL, path, params),
    Header: http.Header{...},
    Body:   []byte{"whatever"},
}, httpsimplified.JSON, &resp)

Use URL func to concatenate a URL and include query params.

Use EncodeBody helper to generate application/x-www-form-urlencoded bodies.

Finally, if http.DefaultClient doesn't rock your boat, you're free to build and execute a request through whatever means necessary and then call JSON, Bytes or None to verify the response status code and handle the body:

req := EncodeBody(&http.Request{
    Method: http.MethodPost,
    URL:    httpsimplified.URL(baseURL, path, nil),
    Header: http.Header{...},
}, url.Params{...})

httpResp, err := myCustomClient.Do(req)
if err != nil { ... }

var resp responseType
err = httpsimplified.JSON(httpResp, &resp)

To handle HTTP basic authentication, use BasicAuth helper:

err := httpsimplified.Get("...", "...", url.Values{...}, http.Header{
    httpsimplified.AuthorizationHeader: []string{httpsimplified.BasicAuth("user", "pw")},
}, httpsimplified.JSON, &resp)

Documentation

Overview

Package httpsimplified sends outgoing HTTP requests via a simple straightforward API distilled from many internal Golang projects at USA Today Network. It embraces Go stdlib types like url.Values and http.Header, provides composable building blocks for more complex use cases and doesn't try to be clever.

Call Get, Post or Put to send a request and parse the response in a single call:

var resp responseType
err := httpsimplified.Get(baseURL, path, params, headers, httpsimplified.JSON, &resp)

where httpsimplified.JSON is a body parser function (we also provide PlainText, Bytes, Raw and None parsers, and you can define your own). See the example for more details.

For more advanced requests, build http.Request yourself and call Perform:

var resp responseType
err := httpsimplified.Perform(&http.Request{
	Method: http.MethodPut,
	URL:    httpsimplified.URL(baseURL, path, params),
	Header: http.Header{...},
	Body:   []byte{"whatever"},
}, httpsimplified.JSON, &resp)

Use URL func to concatenate a URL and include query params.

Use EncodeBody helper to generate application/x-www-form-urlencoded bodies.

Finally, if http.DefaultClient doesn't rock your boat, you're free to build and execute a request through whatever means necessary and then call JSON, Bytes or None to verify the response status code and handle the body:

req := EncodeBody(&http.Request{
	Method: http.MethodPost,
	URL:    httpsimplified.URL(baseURL, path, nil),
	Header: http.Header{...},
}, url.Params{...})

httpResp, err := myCustomClient.Do(req)
if err != nil { ... }

var resp responseType
err = httpsimplified.JSON(httpResp, &resp)

To handle HTTP basic authentication, use BasicAuth helper:

err := httpsimplified.Get("...", "...", url.Values{...}, http.Header{
	httpsimplified.AuthorizationHeader: []string{httpsimplified.BasicAuth("user", "pw")},
}, httpsimplified.JSON, &resp)
Example
package main

import (
	"log"
	"net/url"

	"github.com/andreyvit/httpsimplified"
)

const endpointURL = "http://www.example.com/api/v1"

func main() {
	var resp exampleResponse
	// url.Values is just a map[string][]string
	err := httpsimplified.Get(endpointURL, "examples/foo.json", url.Values{
		"param1": []string{"value1"},
		"param2": []string{"value2"},
	}, nil, httpsimplified.JSON, &resp)

	if err != nil {
		log.Fatal(err)
	}
	log.Printf("foo = %#v", resp)
}

type exampleResponse struct {
	X string
	Y string
}
Output:

Example (CustomHeaders)
package main

import (
	"log"
	"net/http"
	"net/url"

	"github.com/andreyvit/httpsimplified"
)

const endpointURL = "http://www.example.com/api/v1"

func main() {
	var resp exampleResponse
	// url.Values and http.Header are both just map[string][]string
	err := httpsimplified.Get(endpointURL, "examples/foo.json", url.Values{
		"param1": []string{"value1"},
		"param2": []string{"value2"},
	}, http.Header{
		"X-Powered-By":                     []string{"Golang"},
		httpsimplified.AuthorizationHeader: []string{httpsimplified.BasicAuth("user", "secret")},
	}, httpsimplified.JSON, &resp)

	if err != nil {
		log.Fatal(err)
	}
	log.Printf("foo = %#v", resp)
}

type exampleResponse struct {
	X string
	Y string
}
Output:

Index

Examples

Constants

View Source
const (
	// ContentTypeJSON is "application/json"
	ContentTypeJSON = "application/json"

	// ContentTypeFormURLEncoded is "application/x-www-form-urlencoded"
	ContentTypeFormURLEncoded = "application/x-www-form-urlencoded"

	// AuthorizationHeader is the "Authorization" HTTP header
	AuthorizationHeader = "Authorization"
)

Variables

This section is empty.

Functions

func BasicAuth

func BasicAuth(username, password string) string

BasicAuth returns an Authorization header value for HTTP Basic authentication method with the given username and password, i.e. it returns:

"Basic " + base64(username + ":" + password)

Use AuthorizationHeader constant for the header name.

func Bytes

func Bytes(resp *http.Response, result interface{}) error

Bytes is a Parser function that verifies the response status code and reads the entire body into a byte array; result must be a pointer to a []byte variable.

func EncodeBody

func EncodeBody(r *http.Request, params url.Values) *http.Request

EncodeBody encodes the given params into application/x-www-form-urlencoded format and sets the body and Content-Type on the given request.

To properly handle HTTP redirects, both Body and GetBody are set.

func Get

func Get(base, path string, params url.Values, headers http.Header, parser Parser, result interface{}) error

Get builds a GET request with the given URL, parameters and headers, executes it via http.DefaultClient.Do and handles the body using the specified parser function.

base and path are concatenated to form a URL; at least one of them must be provided, but the other one can be an empty string. The resulting URL must be valid and parsable via net/url, otherwise panic ensues.

url.Values and http.Header are just maps that can be provided in place, no need to use their fancy Set or Add methods.

parser can be either JSON, PlainText, Bytes, Raw or None from this package, or your own custom parser function; it will be called with *http.Response and the result you pass in.

func Is4xx

func Is4xx(err error) bool

func Is5xx

func Is5xx(err error) bool

func JSON

func JSON(resp *http.Response, result interface{}) error

JSON is a Parser function that verifies the response status code and content type (which must be ContentTypeJSON) and unmarshals the body into the result variable (which can be anything that you'd pass to json.Unmarshal).

func None

func None(resp *http.Response, result interface{}) error

None is a Parser function that verifies the response status code and discards the response body; result argument is ignored and should be nil.

A typical use would be to pass this function into Get, Post or Perform, but you can also call it directly.

func Perform

func Perform(r *http.Request, parser Parser, result interface{}) error

Perform executes the given request via http.DefaultClient.Do and handles the body using the specified parser function.

parser can be either JSON, Bytes, Raw or None from this package, or your own custom parser function; it will be called with *http.Response and the result you pass in.

func PlainText added in v1.1.0

func PlainText(resp *http.Response, result interface{}) error

PlainText is a Parser function that verifies the response status code and reads the entire body into a string; result must be a pointer to a string variable.

func Post

func Post(base, path string, params url.Values, headers http.Header, parser Parser, result interface{}) error

Post builds a POST request with the given URL, headers and body (which contains the given params in application/x-www-form-urlencoded format), executes it via http.DefaultClient.Do and handles the body using the specified parser function.

base and path are concatenated to form a URL; at least one of them must be provided, but the other one can be an empty string. The resulting URL must be valid and parsable via net/url, otherwise panic ensues.

url.Values and http.Header are just maps that can be provided in place, no need to use their fancy Set or Add methods.

parser can be either JSON, Bytes, Raw or None from this package, or your own custom parser function; it will be called with *http.Response and the result you pass in.

func Put

func Put(base, path string, params url.Values, headers http.Header, parser Parser, result interface{}) error

Put builds a PUT request with the given URL, headers and body (which contains the given params in application/x-www-form-urlencoded format), executes it via http.DefaultClient.Do and handles the body using the specified parser function.

base and path are concatenated to form a URL; at least one of them must be provided, but the other one can be an empty string. The resulting URL must be valid and parsable via net/url, otherwise panic ensues.

url.Values and http.Header are just maps that can be provided in place, no need to use their fancy Set or Add methods.

parser can be either JSON, Bytes, Raw or None from this package, or your own custom parser function; it will be called with *http.Response and the result you pass in.

func Raw

func Raw(resp *http.Response, result interface{}) error

Raw is a Parser function that verifies the response status code and returns the raw *http.Response; result must be a pointer to *http.Response variable.

func StatusCode

func StatusCode(err error) int

func URL

func URL(base, path string, params url.Values) *url.URL

URL returns a *url.URL (conveniently suitable for http.Request's URL field) concatenating the two given URL strings and optionally appending a query string with the given params.

base and path are concatenated to form a URL; at least one of them must be provided, but the other one can be an empty string. The resulting URL must be valid and parsable via net/url, otherwise panic ensues.

url.Values and http.Header are just maps that can be provided in place, no need to use their fancy Set or Add methods.

Types

type ContentTypeError

type ContentTypeError struct {
	StatusCode int

	ContentType string

	ExpectedContentType string
}

func (*ContentTypeError) Error

func (err *ContentTypeError) Error() string

type Error

type Error struct {
	Method string
	Path   string
	Cause  error
}

func (*Error) Error

func (err *Error) Error() string

type Parser

type Parser func(resp *http.Response, result interface{}) error

Parser is a function used to verify and handle the HTTP response. This package provides a number of parser functions, and you can define your own.

type StatusError

type StatusError struct {
	StatusCode int

	ContentType string

	Body interface{}

	DecodingError error
}

func CheckStatusError

func CheckStatusError(err error) *StatusError

func (*StatusError) Error

func (err *StatusError) Error() string

Jump to

Keyboard shortcuts

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