httpclient

package module
v0.0.0-...-0425ac0 Latest Latest
Warning

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

Go to latest
Published: Jul 1, 2021 License: BSD-3-Clause Imports: 12 Imported by: 0

README

httpclient
CircleCI Go Report Card GoDoc

httpclient is a simple convenience package for performing http/api requests in Go. It wraps the standard libraries net/http package to avoid the repetitive http logic you're likely so familiar with. It helps to remove a good amount of the boilerplate involved with writing an http client library. Using the lib is very simple - Below is a very basic example.

Usage

package main

import (
	"log"
	"net/http"

	"s32x.com/httpclient"
)

var user = "s32x"

func main() {
	c := httpclient.New().WithBaseURL("https://api.github.com")

	var ghSuccess interface{} // A generic success response
	var ghError struct {
		Message       string `json:"message"`
		Documentation string `json:"documentation"`
	}

	expected, err := c.
		Getf("/users/%s/repos", user).
		WithExpectedStatus(http.StatusOK).
		WithRetry(5).
		JSONWithError(&ghSuccess, &ghError)
	if err != nil {
		log.Fatal(err)
	}
	if !expected {
		log.Println("Error :", ghError)
	} else {
		log.Println("Success :", ghSuccess)
	}
}

The BSD 3-clause License

Copyright (c) 2021, s32x. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

  • Neither the name of httpclient nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Transports = map[string]TransportFunc{
	"http": func(addr string) *http.Transport {
		u, _ := url.Parse("http://" + addr)
		return &http.Transport{Proxy: http.ProxyURL(u)}
	},
	"https": func(addr string) *http.Transport {
		u, _ := url.Parse("http://" + addr)
		return &http.Transport{Proxy: http.ProxyURL(u)}
	},
	"socks4": func(addr string) *http.Transport {
		return &http.Transport{Dial: socks.Dial("socks4://" + addr)}
	},
	"socks5": func(addr string) *http.Transport {
		u, _ := url.Parse("socks5://" + addr)
		return &http.Transport{Proxy: http.ProxyURL(u)}
	},
}

Transports is a map of proxy TransportFuncs keyed by their protocol

Functions

This section is empty.

Types

type Client

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

Client is an http.Client wrapper

func New

func New() *Client

New creates a new Client reference given a client timeout

func (*Client) Client

func (c *Client) Client() *http.Client

Client is a getter that returns a reference to the underlying http Client

func (*Client) Delete

func (c *Client) Delete(path string) *Request

Delete takes a path and returns a prepopulated Delete request

func (*Client) Deletef

func (c *Client) Deletef(format string, a ...interface{}) *Request

Deletef takes a format and a variadic of arguments and returns a prepopulated Delete request

func (*Client) Get

func (c *Client) Get(path string) *Request

Get takes a path and returns a prepopulated Get request

func (*Client) Getf

func (c *Client) Getf(format string, a ...interface{}) *Request

Getf takes a format and a variadic of arguments and returns a prepopulated Get request

func (*Client) Head

func (c *Client) Head(path string) *Request

Head takes a path and returns a prepopulated Head request

func (*Client) Headf

func (c *Client) Headf(format string, a ...interface{}) *Request

Headf takes a format and a variadic of arguments and returns a prepopulated Head request

func (*Client) Patch

func (c *Client) Patch(path string) *Request

Patch takes a path and returns a prepopulated Patch request

func (*Client) Patchf

func (c *Client) Patchf(format string, a ...interface{}) *Request

Patchf takes a format and a variadic of arguments and returns a prepopulated Patch request

func (*Client) Post

func (c *Client) Post(path string) *Request

Post takes a path and returns a prepopulated Post request

func (*Client) Postf

func (c *Client) Postf(format string, a ...interface{}) *Request

Postf takes a format and a variadic of arguments and returns a prepopulated Post request

func (*Client) Put

func (c *Client) Put(path string) *Request

Put takes a path and returns a prepopulated Put request

func (*Client) Putf

func (c *Client) Putf(format string, a ...interface{}) *Request

Putf takes a format and a variadic of arguments and returns a prepopulated Put request

func (*Client) Request

func (c *Client) Request(method, path string) *Request

Request creates a new Request copying configuration from the base Client

func (*Client) WithBaseURL

func (c *Client) WithBaseURL(url string) *Client

WithBaseURL sets the baseURL on the Client

func (*Client) WithClient

func (c *Client) WithClient(client *http.Client) *Client

WithClient sets the http client on the Client

func (*Client) WithHeader

func (c *Client) WithHeader(key, value string) *Client

WithHeader sets the headers on the Client

func (*Client) WithProxy

func (c *Client) WithProxy(protocol, addr string) *Client

WithProxy sets a proxy on the Client

func (*Client) WithTimeout

func (c *Client) WithTimeout(timeout time.Duration) *Client

WithTimeout sets the timeout on the http Client

func (*Client) WithTransport

func (c *Client) WithTransport(transport http.RoundTripper) *Client

WithTransport sets teh transport on the http Client

type Request

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

Request is a type used for configuring, performing and decoding HTTP requests

func (*Request) Bytes

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

Bytes is a convenience method that handles executing, defer closing, and decoding the body into a slice of bytes before returning

func (*Request) Do

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

Do performs the base request and returns a populated Response NOTE: As with the standard library, when calling Do you must remember to close the response body : res.Body.Close()

func (*Request) Error

func (r *Request) Error() error

Error performs the request and returns any errors that result from the Do

func (*Request) JSON

func (r *Request) JSON(out interface{}) error

JSON is a convenience method that handles executing, defer closing, and decoding the JSON body into the passed interface before returning

func (*Request) JSONWithError

func (r *Request) JSONWithError(out interface{}, errOut interface{}) (bool, error)

JSONWithError is identical to the JSON(...) method but also takes an errOut interface for when the status code isn't expected. In this case the response body will be decoded into the errOut interface and the boolean (expected) will return false

func (*Request) String

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

String is a convenience method that handles executing, defer closing, and decoding the body into a string before returning

func (*Request) WithBody

func (r *Request) WithBody(body io.ReadWriter) *Request

WithBody sets the body on the request with the passed io.ReadWriter

func (*Request) WithBytes

func (r *Request) WithBytes(body []byte) *Request

WithBytes sets the passed bytes as the body to be used on the Request

func (*Request) WithContentType

func (r *Request) WithContentType(typ string) *Request

WithContentType sets the content-type that will be set in the headers on the Request

func (*Request) WithContext

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

WithContext sets the context on the Request

func (*Request) WithExpectedStatus

func (r *Request) WithExpectedStatus(expectedStatusCode int) *Request

WithExpectedStatus sets the desired status-code that will be a success. If the expected status code isn't received an error will be returned or the request will be retried if a count has been set with WithRetry(...)

func (*Request) WithForm

func (r *Request) WithForm(data url.Values) *Request

WithForm encodes and sets the passed url.Values as the body to be used on the Request

func (*Request) WithHeader

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

WithHeader sets a header that will be used on the Request

func (*Request) WithJSON

func (r *Request) WithJSON(body interface{}) *Request

WithJSON sets the JSON encoded passed interface as the body to be used on the Request

func (*Request) WithRetry

func (r *Request) WithRetry(retryCount int) *Request

WithRetry sets the desired number of retries on the Request Note: In order to trigger retries you must set an expected status code with the WithExpectedStatus(...) method

func (*Request) WithString

func (r *Request) WithString(body string) *Request

WithString sets the passed string as the body to be used on the Request

func (*Request) WithXML

func (r *Request) WithXML(body interface{}) *Request

WithXML sets the XML encoded passed interface as the body to be used on the Request

func (*Request) XML

func (r *Request) XML(out interface{}) error

XML is a convenience method that handles executing, defer closing, and decoding the XML body into the passed interface before returning

func (*Request) XMLWithError

func (r *Request) XMLWithError(out interface{}, errOut interface{}) (bool, error)

XMLWithError is identical to the XML(...) method but also takes an errOut interface for when the status code isn't expected. In this case the response body will be decoded into the errOut interface and the boolean (expected) will return false

type Response

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

Response contains the raw http.Response reference OR any error that took place while performing the request

func (*Response) Body

func (r *Response) Body() io.ReadCloser

Body returns the io Readcloser body on the Responses http Response

func (*Response) Bytes

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

Bytes attempts to return the decoded response as bytes

func (*Response) Close

func (r *Response) Close() error

Close closes the response body on the Responses http Response

func (*Response) ContentType

func (r *Response) ContentType() string

ContentType returns the content-type header found on the response

func (*Response) Header

func (r *Response) Header() http.Header

Header returns the Header on the Responses http Response

func (*Response) JSON

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

JSON attempts to JSON decode the response body into the passed interface

func (*Response) Response

func (r *Response) Response() *http.Response

Response returns the http Response reference that is on the Response

func (*Response) Status

func (r *Response) Status() string

Status returns the status message on the Response

func (*Response) StatusCode

func (r *Response) StatusCode() int

StatusCode returns the status code found on the Response

func (*Response) String

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

String attempts to return the decoded response as a string

func (*Response) XML

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

XML attempts to XML decode the response body into the passed interface

type TransportFunc

type TransportFunc func(addr string) *http.Transport

TransportFunc takes an address to a proxy server and returns a fully populated http Transport

Jump to

Keyboard shortcuts

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