structuredhttp

package module
v0.0.0-...-64be4e6 Latest Latest
Warning

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

Go to latest
Published: Jul 5, 2021 License: MPL-2.0 Imports: 13 Imported by: 0

README

structuredhttp

A lightweight structured HTTP client for Go with no third party dependencies. The client works by chaining functions:

package main

import (
	"github.com/jakemakesstuff/structuredhttp"
	"time"
)

func main() {
	response, err := structuredhttp.GET(
		"https://httpstat.us/200").Timeout(10 * time.Second).Run()

	if err != nil {
		panic(err)
	}

	err = response.RaiseForStatus()
	if err != nil {
		panic(err)
	}
 
	println("Ayyyy! A 200!")
}

Making a request

To make a request, you need to call the function representing the HTTP method. For example, if you want to make a HTTP GET request, you will call the GET function. There are several functions you can call in the request chain:

  • Timeout - Check the "Handling timeouts" documentation below.
  • Header - This adds a header into your request. This function takes a key and a value.
  • Bytes - Puts the bytes specified into the body.
  • JSON - Serializes the item specified into JSON (make sure you provide a pointer) and puts it into the body.
  • Reader - Allows you to provide your own I/O reader.
  • URLEncodedForm - This will take the values specified and turn it into a URL encoded form.
  • MultipartForm - This will take the buffer and content type after the creation of a multipart form and handle it.
  • Plugin - This will pass through to a third party function specified. The plugin will need to take *structuredhttp.Request as an argument.
  • Query - This adds a URL query argument to the URL.

After you have made the request chain, you should call Run. This function will then return a pointer to the Response structure (described below) and an error which will not be null if something went wrong.

Handling timeouts

There are 2 ways to handle timeouts:

  1. Call the Timeout function in the request chain: Calling the timeout function in the request chain will override the default timeout.
  2. Set a default timeout: To set a default timeout, you can call SetDefaultTimeout:
    structuredhttp.SetDefaultTimeout(5 * time.Second)
    

The Response structure

The response structure has several useful functions:

  • Bytes - This returns the response as bytes.
  • JSON - This returns the response as an interface which can be casted to different types.
  • RaiseForStatus - This just returns an error. The error will not be null if it's a HTTP error.
  • Text - This returns the response as text.

If you need the raw response, the RawResponse attribute contains a pointer to the http.Response from the request.

Request error handling

The Request structure has an Error attribute. If there is an error, the error should be attached to this attribute. Any other functions in the chain will be skipped, and in the Run function the error will be thrown.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultTimeout = time.Duration(0)

DefaultTimeout defines the default timeout.

Functions

func SetDefaultTimeout

func SetDefaultTimeout(Timeout time.Duration)

SetDefaultTimeout allows the user to set the default timeout in this library.

Types

type Batch

type Batch []*Request

Batch is used to define a request batch.

func (Batch) All

func (b Batch) All() ([]*Response, error)

All is used to execute a batch job and return the pure responses. If one fails, the first error is returned.

func (Batch) Map

func (b Batch) Map(f func(*Response) (interface{}, error)) *BatchMapper

Map is used to create a new batch mapper builder.

type BatchMapper

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

BatchMapper is used to handle mapping a Batch to values.

func (*BatchMapper) All

func (b *BatchMapper) All() ([]interface{}, error)

All is used to execute a batch job and return the mapped responses. If one fails, the first error is returned.

func (*BatchMapper) Map

func (b *BatchMapper) Map(f func(interface{}) (interface{}, error)) *BatchMapper

Map is used to handle adding a mapper function to the chain.

type Parser

type Parser func(responseBytes []byte, into interface{}) error

Parser is a response body parser. These can be found in the data package.

type Request

type Request struct {
	URL            string            `json:"url"`
	Method         string            `json:"method"`
	Headers        map[string]string `json:"headers"`
	CurrentTimeout *time.Duration    `json:"timeout"`
	CurrentReader  io.Reader         `json:"-"`
	Error          *error            `json:"-"`
}

Request defines the request that will be ran.

func DELETE

func DELETE(URL string) *Request

DELETE adds support for a DELETE request.

func GET

func GET(URL string) *Request

GET adds support for a GET request.

func HEAD(URL string) *Request

HEAD adds support for a HEAD request.

func OPTIONS

func OPTIONS(URL string) *Request

OPTIONS adds support for a OPTIONS request.

func PATCH

func PATCH(URL string) *Request

PATCH adds support for a PATCH request.

func POST

func POST(URL string) *Request

POST adds support for a POST request.

func PUT

func PUT(URL string) *Request

PUT adds support for a PUT request.

func (*Request) Bytes

func (r *Request) Bytes(Data []byte) *Request

Bytes sets the data to the bytes specified.

func (*Request) Header

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

Header sets a header.

func (*Request) JSON

func (r *Request) JSON(Data interface{}) *Request

JSON sets the data to the JSON specified.

func (*Request) MultipartForm

func (r *Request) MultipartForm(Buffer *bytes.Buffer, ContentType string) *Request

MultipartForm sets the data to a multipart form.

func (*Request) Plugin

func (r *Request) Plugin(Function func(r *Request)) *Request

Plugin allows for third party functions to be chained into the request.

func (*Request) Query

func (r *Request) Query(Key string, Value string) *Request

Query adds a URL query argument to the URL.

func (*Request) Reader

func (r *Request) Reader(Data io.Reader) *Request

Reader sets the IO reader to the one specified.

func (*Request) Run

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

Run executes the request.

func (*Request) Serialize

func (r *Request) Serialize(data interface{}, serializer Serializer) *Request

Serialize sets response headers and calls Bytes with the serialized body.

func (*Request) Timeout

func (r *Request) Timeout(Value time.Duration) *Request

Timeout sets a timeout. 0 is infinite.

func (*Request) URLEncodedForm

func (r *Request) URLEncodedForm(Data url.Values) *Request

URLEncodedForm sets the data to a URL encoded form.

type Response

type Response struct {
	RawResponse *http.Response
}

Response defines the higher level HTTP response.

func (*Response) Bytes

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

Bytes gets the response as bytes.

func (*Response) JSON

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

JSON returns the result as a interface which can be converted how the user wishes.

func (*Response) JSONToPointer

func (r *Response) JSONToPointer(Pointer interface{}) error

JSONToPointer is used to be a non-generic JSON handler when you have a pointer.

func (*Response) Parse

func (r *Response) Parse(parser Parser) (interface{}, error)

Parse parses the response body's bytes with a Parser.

func (*Response) RaiseForStatus

func (r *Response) RaiseForStatus() error

RaiseForStatus throws a error if the request is a 4XX/5XX.

func (*Response) Text

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

Text returns the status as a string.

type RouteHandler

type RouteHandler struct {
	BaseURL string            `json:"base_url"`
	Timeout *time.Duration    `json:"-"`
	Headers map[string]string `json:"headers"`
}

RouteHandler defines the base HTTP URL/timeout which is used for routes.

func (*RouteHandler) DELETE

func (r *RouteHandler) DELETE(Path string) *Request

DELETE does a DELETE request based on this base.

func (*RouteHandler) GET

func (r *RouteHandler) GET(Path string) *Request

GET does a GET request based on this base.

func (*RouteHandler) GenerateURL

func (r *RouteHandler) GenerateURL(Path string) (string, error)

GenerateURL takes a path and returns the URL with the path added.

func (*RouteHandler) HEAD

func (r *RouteHandler) HEAD(Path string) *Request

HEAD does a HEAD request based on this base.

func (*RouteHandler) OPTIONS

func (r *RouteHandler) OPTIONS(Path string) *Request

OPTIONS does a OPTIONS request based on this base.

func (*RouteHandler) PATCH

func (r *RouteHandler) PATCH(Path string) *Request

PATCH does a PATCH request based on this base.

func (*RouteHandler) POST

func (r *RouteHandler) POST(Path string) *Request

POST does a POST request based on this base.

func (*RouteHandler) PUT

func (r *RouteHandler) PUT(Path string) *Request

PUT does a PUT request based on this base.

type Serializer

type Serializer struct {
	Encode      func(data interface{}) ([]byte, error)
	ContentType string
}

Serializer is a request body serializer.

Jump to

Keyboard shortcuts

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