request

package module
v0.0.0-...-4d175e7 Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2018 License: MIT Imports: 12 Imported by: 0

README

go-request

This project implements a simple HTTP requests builder with a fluent API; rrequest submission and response handling is out of scope.

Usage

The library can be imported via

import (
	"github.com/dihedron/go-request"
)

and provides a simple factory pattern that can be used to add information and finally retrieve an http.Request object. The Builder is available under the request namespace. Typical usage would be along the following lines:

req, _ := request.
	New("").                                        // create the factory
	Post().                                         // POST HTTP method
	UserAgent("myUserAgent/1.0").                   // sets the user agent
	Base("https://www.example.com/").               // base URL for requests
	Path("api/v2/login?param1=value1").             // extra request path
	Add().                                          // start adding
	QueryParameter("param1", "value1a", "value1b").	// adds a query param to URL
	QueryParameter("param2", "value2").             // adds another query param
	Header("X-Auth-Token", "1234567890abcdef").     // adds a header
	WithJSONEntity(myTaggedStruct).                 // adds the request body from a struct
	Make()

Let's break it apart, line by line:

  1. the first instruction (New("")) creates a new builder; this method can be used to pass in the request's URL, or it can be specified later, as in this example;
  2. the HTTP method is POST; if not specified, the default is GET;
  3. the second instruction (UserAgent()) adds the User-Agent header to the request; a special facility is provided for the User-Agent and Content-Type headers since these are more common used than others;
  4. the Base() call sets the base URL for requests generated from this builder; this can be very useful when creating sub-builders, because they will all share the same base URL and have different paths;
  5. Path() sets the resource path; paths can be absolute (in which case the base path should have a trailing slash) or relative and include ../; if the path includes query parameters, they will be preserved when the request is generated;
  6. Add() opens a section where the builder accepts query parameter and header values that will be added to the request; other accepted operations are Set() (which replaces query parameters and headers if already present), 'Del() (which removes headers and query parameter with the given key), Remove() (which removes headers and query parameters whose keys match the given regular expression);
  7. QueryParameter() and Header() are used to specify query parameters and headers, respectively, that will be added to the builder;
  8. WithJSONEntity() (and its XML counterpart WithXMLEntity()) is a way to add the request entity (payload) by passing in a tagged struct; all fields marked with json (and xml) will be stored as part of the JSON (XML) request body; these methods also have the side effect of setting the USer-Agent if none was set already;
  9. Make() creates the http.Request.

The library provides the following additional facilities:

  • reading of raw data into the request body (see WithEntity(io.Reader)), as follows:
file, _ := os.Open("path/file.ext")
req, _ := request.
	New("").
	// more methods here...
	WithEntity(bufio.NewReader(file))
  • populating headers ad query parameters from a struct, whose fields are tagged with header and parameter tags respectively, or from a map[string][]string (see HeaderFrom() and QueryParametersFrom()).
req, _ := request.
	New("").
	// more methods here...
	Set().
	QueryParametersFrom(myMapQP).
	QueryParametersFrom(myStructQP).
	HeadersFrom(&myMapH).
	HeadersFrom(&myStructH).
	Make()

Note from the example that both struct, map[string][]string and their pointers are supported.

A Builder can be used to create sub-Builders that has a copy of the parent's headers and query parameters at that moment, plus a shared reference to the entity ioReader:

parent, _ := request.
	New("").
	Base("https://www.example.com/")
	// more methods here...
child := parent.New() // shares headers and query parameters.

Contributing

All contributions are welcome provided they don't spoil the simplicity of the API and that complete coverage with automatic unit tests is provided.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Builder

type Builder struct {
	// contains filtered or unexported fields
}

Builder is the HTTP request builder; it can be used to create child request factories, with specialised BaseURLs or other parameters; when a sub-builder is generated, it will share the Method and BaseURL by value and all other firlds by pointer, so any change in sub-factories will affect the parent too.

func New

func New(url string) *Builder

New returns a new request builder; the URL can be omitted and specified later via Base() or Path().

func (*Builder) Add

func (f *Builder) Add() *Builder

Add is used to provide a fluent API by which it is possible to add query parameters and headers without having many different methods or intermediate objects; this method relies on an internal Builder field (named op), which will be set to the "add" value and will instruct the following QueryParameter() and Header() methods to add the passed values to the current set for the given key.

func (*Builder) Base

func (f *Builder) Base(url string) *Builder

Base sets the base URL. If you intend to extend the url with Path, the URL should be specified with a trailing slash.

func (*Builder) Connect

func (f *Builder) Connect() *Builder

Connect sets the builder method to "CONNECT" and returns an http.Request.

func (*Builder) ContentType

func (f *Builder) ContentType(contentType string) *Builder

ContentType sets the content type information in the request builder; the previous value is discarded.

func (*Builder) Del

func (f *Builder) Del() *Builder

Del is used to provide a fluent API by which it is possible to replace query parameters and headers without having many different methods or intermediate objects; this method relies on an internal Builder field (named op), which will be set to the "set" value and will instruct the following QueryParameter() and Header() methods to replace the current set of values for the given key with the passed values.

func (*Builder) Delete

func (f *Builder) Delete() *Builder

Delete sets the builder method to "DELETE" and returns an http.Request.

func (*Builder) Get

func (f *Builder) Get() *Builder

Get sets the builder method to "GET" and returns an http.Request.

func (*Builder) Head

func (f *Builder) Head() *Builder

Head sets the builder method to "HEAD" and returns an http.Request.

func (*Builder) Header

func (f *Builder) Header(key string, values ...string) *Builder

Header adds, sets or removes the given set of values to the URL's headers; if the header is being removed, there is no need to specify any value; if the header is being reset, the key is regarded as a regular expression.

func (*Builder) HeadersFrom

func (f *Builder) HeadersFrom(source interface{}) *Builder

HeadersFrom adds, sets or removes values extracted from a struct (and tagged with "header") or from a map[string][]string to the URL's headers; if the headers are being removed, there is no need to specify any value in the input struct/map; if the headers are being reset, the keys are regarded as regular expressions.

func (*Builder) Make

func (f *Builder) Make() (*http.Request, error)

Make creates a new http.Request from the information available in the Builder.

func (*Builder) Method

func (f *Builder) Method(method string) *Builder

Method sets the default HTTP method for factoory-generated requests.

func (*Builder) New

func (f *Builder) New(method, url string) *Builder

New clones the current builder and can optionally specify the request method and/or the request URL.

func (*Builder) Options

func (f *Builder) Options() *Builder

Options sets the builder method to "OPTIONS" and returns an http.Request.

func (*Builder) Patch

func (f *Builder) Patch() *Builder

Patch sets the builder method to "PATCH" and returns an http.Request.

func (*Builder) Path

func (f *Builder) Path(path string) *Builder

Path overrides the builder URL; absolute and relative URLs can be used. TODO: improve documentation showing relative paths

func (*Builder) Post

func (f *Builder) Post() *Builder

Post sets the builder method to "POST" and returns an http.Request.

func (*Builder) Put

func (f *Builder) Put() *Builder

Put sets the builder method to "PUT" and returns an http.Request.

func (*Builder) QueryParameter

func (f *Builder) QueryParameter(key string, values ...string) *Builder

QueryParameter adds, sets or removes the given set of values to the URL's query parameters; if the query parameter is being removed, there is no need to specify any value; if the query parameter is being reset, the key is regarded as a regular expression.

func (*Builder) QueryParametersFrom

func (f *Builder) QueryParametersFrom(source interface{}) *Builder

QueryParametersFrom adds, sets or removes values extracted from a struct (and tagged with "parameter") or from a map[string][]string to the URL's query parameters; if the query parameters are being removed, there is no need to specify any value in the input struct/map; if the query parameters are being reset, the keys are regarded as regular expressions.

func (*Builder) Remove

func (f *Builder) Remove() *Builder

Remove is used to provide a fluent API by which it is possible to remove the values of query parameters and headers whose keys match a regular exception.

func (*Builder) Set

func (f *Builder) Set() *Builder

Set is used to provide a fluent API by which it is possible to replace query parameters and headers without having many different methods or intermediate objects; this method relies on an internal Builder field (named op), which will be set to the "set" value and will instruct the following QueryParameter() and Header() methods to replace the current set of values for the given key with the passed values.

func (Builder) String

func (f Builder) String() string

String prints the current request builder internal state as a string.

func (*Builder) Trace

func (f *Builder) Trace() *Builder

Trace sets the builder method to "TRACE" and returns an http.Request.

func (*Builder) UserAgent

func (f *Builder) UserAgent(userAgent string) *Builder

UserAgent sets the user agent information in the request builder; the previous value is discarded.

func (*Builder) Variable

func (f *Builder) Variable(key string, value interface{}) *Builder

Variable adds, sets or removes the given value to the URL's variables; if the variable is being removed, there is no need to specify the value; both setting and adding a value for a given variable effectively replace its value.

func (*Builder) VariablesFrom

func (f *Builder) VariablesFrom(source interface{}) *Builder

VariablesFrom adds/sets or removes values extracted from a struct (and tagged with "variable") or from a map[string]string to the URL's variables; if the variables are being removed, there is no need to specify any value in the input struct/map; if the variables are being reset, the keys are regarded as regular expressions.

func (*Builder) WithEntity

func (f *Builder) WithEntity(entity io.Reader) *Builder

WithEntity sets the io.Reader from which the request body (payload) will be read; if nil is passed, the request will have no payload; the Content-Type MUST be provoded separately.

func (*Builder) WithJSONEntity

func (f *Builder) WithJSONEntity(entity interface{}) *Builder

WithJSONEntity sets an io.Reader that returns a JSON fragment as per the input struct; if no Content-Type has been set already, the method will automatically set it to "application/json".

func (*Builder) WithXMLEntity

func (f *Builder) WithXMLEntity(entity interface{}) *Builder

WithXMLEntity sets an io.Reader that returns an XML fragment as per the input struct; if no Content-Type has been set already, the method will automatically set it to "application/xml".

type Tag

type Tag struct {
	// contains filtered or unexported fields
}

Tag represents the value of a tag on a tagged struct field.

func NewTag

func NewTag(tag string) Tag

NewTag creates a new Tag struct from the given tag value.

func (Tag) IsIgnore

func (t Tag) IsIgnore() bool

IsIgnore returns whether the tagged field struct contains the "-" (dash) character that is usually employed to say that the field should be ignored with respect to this specific tag handling (e.g. `json:"-"` means "do not marshal when writing to JSON).

func (Tag) IsMissing

func (t Tag) IsMissing() bool

IsMissing returns whether the tag on the field is missing/invalid (i.e. empty).

func (Tag) IsOmitEmpty

func (t Tag) IsOmitEmpty() bool

IsOmitEmpty returns whether the tag should be ignored when it contains an empty value (e.g. a null pointer).

func (Tag) Name

func (t Tag) Name() string

Name extracts the name of the tag, that is the first value in the list of comma-separated values that can be given in a tagged struct field.

Jump to

Keyboard shortcuts

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