httpclient

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

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

Go to latest
Published: Feb 28, 2024 License: MIT Imports: 23 Imported by: 12

README

httpclient

More flexible http client library for Go

Installation

$ go get github.com/gobs/httpclient

Documentation

http://godoc.org/github.com/gobs/httpclient

Documentation

Index

Constants

View Source
const (
	DefaultTimeout  = 30 * time.Second
	DefaultMaxConns = 50
)

Variables

View Source
var (
	// we use our own default client, so we can change the TLS configuration
	DefaultClient                      = &http.Client{Timeout: DefaultTimeout}
	DefaultTransport http.RoundTripper = http.DefaultTransport.(*http.Transport).Clone()

	NoRedirect       = errors.New("No redirect")
	TooManyRedirects = errors.New("stopped after 10 redirects")
	NotModified      = errors.New("Not modified")
)
View Source
var (
	HEAD   = Method("HEAD")
	GET    = Method("GET")
	POST   = Method("POST")
	PUT    = Method("PUT")
	DELETE = Method("DELETE")
)
View Source
var HttpFileNoHead = false
View Source
var HttpFileRetries = 10
View Source
var HttpFileRetryWait = 60 * time.Second

Functions

func AllowInsecure

func AllowInsecure(insecure bool)

Allow connections via HTTPS even if something is wrong with the certificate (self-signed or expired)

func CloseResponse

func CloseResponse(r *http.Response)

CloseResponse makes sure we close the response body

func DisableHttp2

func DisableHttp2()

Disable HTTP/2 client support. This is useful for doing stress tests when you want to create a lot of concurrent HTTP/1.1 connection (the HTTP/2 client would try to multiplex the requests on a single connection).

func LoggedTransport

func LoggedTransport(t http.RoundTripper, requestBody, responseBody, timing bool) http.RoundTripper

Wrap input transport into a LoggingTransport

func ParamValues

func ParamValues(params map[string]interface{}, q url.Values) url.Values

ParamValues fills the input url.Values according to params

func SetTimeout

func SetTimeout(t time.Duration)

Set connection timeout

func StartLogging

func StartLogging(requestBody, responseBody, timing bool)

Enable logging requests/response headers

if requestBody == true, also log request body if responseBody == true, also log response body if timing == true, also log elapsed time

func StopLogging

func StopLogging()

Disable logging requests/responses

func URLWithParams

func URLWithParams(base string, params map[string]interface{}) (u *url.URL)

func URLWithPathParams

func URLWithPathParams(base string, path string, params map[string]interface{}) (u *url.URL)

Given a base URL and a bag of parameteters returns the URL with the encoded parameters

Types

type DebugLog

type DebugLog bool

func (DebugLog) Printf

func (d DebugLog) Printf(fmt string, args ...interface{})

func (DebugLog) Println

func (d DebugLog) Println(args ...interface{})

type HttpClient

type HttpClient struct {

	// the base URL for this client
	BaseURL *url.URL

	// overrides Host header
	Host string

	// the client UserAgent string
	UserAgent string

	// Common headers to be passed on each request
	Headers map[string]string

	// Cookies to be passed on each request
	Cookies []*http.Cookie

	// if FollowRedirects is false, a 30x response will be returned as is
	FollowRedirects bool

	// if HeadRedirects is true, the client will follow the redirect also for HEAD requests
	HeadRedirects bool

	// if Verbose, log request and response info
	Verbose bool

	// if Close, all requests will set Connection: close
	// (no keep-alive)
	Close bool
	// contains filtered or unexported fields
}

http.Client with some defaults and stuff

func NewHttpClient

func NewHttpClient(base string) (httpClient *HttpClient)

Create a new HttpClient

func (*HttpClient) AllowInsecure

func (self *HttpClient) AllowInsecure(insecure bool)

Allow connections via HTTPS even if something is wrong with the certificate (self-signed or expired)

func (*HttpClient) Clone

func (self *HttpClient) Clone() *HttpClient

Clone an HttpClient (re-use the same http.Client but duplicate the headers)

func (*HttpClient) Delete

func (self *HttpClient) Delete(path string, headers map[string]string) (*HttpResponse, error)

Execute a DELETE request

func (*HttpClient) Do

func (self *HttpClient) Do(req *http.Request) (*HttpResponse, error)

Execute request

func (*HttpClient) Get

func (self *HttpClient) Get(path string, params map[string]interface{}, headers map[string]string) (*HttpResponse, error)

Execute a GET request

func (*HttpClient) GetCookieJar

func (self *HttpClient) GetCookieJar() http.CookieJar

Get current CookieJar

func (*HttpClient) GetTimeout

func (self *HttpClient) GetTimeout() time.Duration

Get connection timeout

func (*HttpClient) GetTransport

func (self *HttpClient) GetTransport() http.RoundTripper

Get current Transport

func (*HttpClient) Head

func (self *HttpClient) Head(path string, params map[string]interface{}, headers map[string]string) (*HttpResponse, error)

Execute a HEAD request

func (*HttpClient) Path

func (c *HttpClient) Path(path string) RequestOption

func (*HttpClient) Post

func (self *HttpClient) Post(path string, content io.Reader, headers map[string]string) (*HttpResponse, error)

Execute a POST request

func (*HttpClient) PostForm

func (self *HttpClient) PostForm(path string, data url.Values, headers map[string]string) (*HttpResponse, error)

func (*HttpClient) Put

func (self *HttpClient) Put(path string, content io.Reader, headers map[string]string) (*HttpResponse, error)

Execute a PUT request

func (*HttpClient) Request

func (self *HttpClient) Request(method string, urlpath string, body io.Reader, headers map[string]string) (req *http.Request)

Create a request object given the method, path, body and extra headers

func (*HttpClient) SendRequest

func (self *HttpClient) SendRequest(options ...RequestOption) (*HttpResponse, error)

Execute request

func (*HttpClient) SetBase

func (self *HttpClient) SetBase(base string) error

Set Base

func (*HttpClient) SetCookieJar

func (self *HttpClient) SetCookieJar(jar http.CookieJar)

Set CookieJar

func (*HttpClient) SetTimeout

func (self *HttpClient) SetTimeout(t time.Duration)

Set connection timeout

func (*HttpClient) SetTransport

func (self *HttpClient) SetTransport(tr http.RoundTripper)

Set Transport

func (*HttpClient) StartLogging

func (self *HttpClient) StartLogging(requestBody, responseBody, timing bool)

Enable request logging for this client

func (*HttpClient) StopLogging

func (self *HttpClient) StopLogging()

Disable request logging for this client

func (*HttpClient) UploadFile

func (self *HttpClient) UploadFile(method, path, fileParam, filePath string, payload []byte, params map[string]string, headers map[string]string) (*HttpResponse, error)

Upload a file via form

type HttpError

type HttpError struct {
	Code       int
	Message    string
	RetryAfter int
	Body       []byte
	Header     http.Header
}

HTTP error

func (HttpError) Error

func (e HttpError) Error() string

func (HttpError) String

func (e HttpError) String() string

type HttpFile

type HttpFile struct {
	Url     string
	Headers map[string]string
	Debug   bool

	Buffer []byte
	// contains filtered or unexported fields
}

HttpFile is a file-like object that allows reading and seeking from an http resources (via an HTTP GET with Range request)

func OpenHttpFile

func OpenHttpFile(url string, headers map[string]string) (*HttpFile, error)

Creates an HttpFile object. At this point the "file" is "open"

func (*HttpFile) Close

func (f *HttpFile) Close() error

The Closer interface

func (*HttpFile) Read

func (f *HttpFile) Read(p []byte) (int, error)

The Reader interface

func (*HttpFile) ReadAt

func (f *HttpFile) ReadAt(p []byte, off int64) (int, error)

The ReaderAt interface

func (*HttpFile) Seek

func (f *HttpFile) Seek(offset int64, whence int) (int64, error)

The Seeker interface

func (*HttpFile) Size

func (f *HttpFile) Size() int64

Returns the file size

type HttpFileError

type HttpFileError struct {
	Err error
}

HttpFileError wraps a network error

func (*HttpFileError) Error

func (e *HttpFileError) Error() string

func (*HttpFileError) Temporary

func (e *HttpFileError) Temporary() bool

func (*HttpFileError) Timeout

func (e *HttpFileError) Timeout() bool

type HttpResponse

type HttpResponse struct {
	http.Response
}

A wrapper for http.Response

func CheckStatus

func CheckStatus(r *HttpResponse, err error) (*HttpResponse, error)

CheckStatus returns err if not null or an HTTP status if the response was not "succesfull"

usage:

resp, err := httpclient.CheckStatus(httpclient.SendRequest(params...))

func Get

func Get(urlStr string, params map[string]interface{}) (*HttpResponse, error)

http.Get with params

func Post

func Post(urlStr string, params map[string]interface{}) (*HttpResponse, error)

http.Post with params

func (*HttpResponse) Close

func (r *HttpResponse) Close()

Close makes sure that all data from the body is read before closing the reader.

If that is not the desider behaviour, just call HttpResponse.Body.Close()

func (*HttpResponse) Content

func (resp *HttpResponse) Content() []byte

Read the body

func (*HttpResponse) ContentDisposition

func (r *HttpResponse) ContentDisposition() (ctype, name, filename string)

ContentDisposition returns the content disposition type, field name and filename values

func (*HttpResponse) ContentType

func (r *HttpResponse) ContentType() string

ContentType returns the response content type

func (*HttpResponse) Json

func (resp *HttpResponse) Json() (json *simplejson.Json)

Try to parse the response body as JSON

func (*HttpResponse) JsonDecode

func (resp *HttpResponse) JsonDecode(out interface{}, strict bool) error

JsonDecode decodes the response body as JSON into specified structure

func (*HttpResponse) ResponseError

func (r *HttpResponse) ResponseError() error

ResponseError checks the StatusCode and return an error if needed. The error is of type HttpError

func (*HttpResponse) XmlDecode

func (resp *HttpResponse) XmlDecode(out interface{}, strict bool) error

XmlDecode decodes the response body as XML into specified structure

type LoggingTransport

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

func (*LoggingTransport) RoundTrip

func (lt *LoggingTransport) RoundTrip(req *http.Request) (resp *http.Response, err error)

type ProgressReader

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

func NewProgressReader

func NewProgressReader(r io.Reader, c byte, threshold int) *ProgressReader

func (*ProgressReader) Close

func (p *ProgressReader) Close() error

func (*ProgressReader) Read

func (p *ProgressReader) Read(b []byte) (int, error)

type RequestOption

type RequestOption func(req *http.Request) (*http.Request, error)

func Accept

func Accept(ct string) RequestOption

set the Accept header

func Body

func Body(r io.Reader) RequestOption

set the request body as an io.Reader

func ContentLength

func ContentLength(l int64) RequestOption

set the Content-Length header

func ContentType

func ContentType(ct string) RequestOption

set the Content-Type header

func Context

func Context(ctx context.Context) RequestOption

set request context

func FormBody

func FormBody(params map[string]interface{}) RequestOption

set the request body as a form object

func Header(headers map[string]string) RequestOption

set specified HTTP headers

func JsonBody

func JsonBody(body interface{}) RequestOption

set the request body as a JSON object

func Method

func Method(m string) RequestOption

Set the request method

func Params

func Params(params map[string]interface{}) RequestOption

set the request URL parameters

func Path

func Path(path string) RequestOption

set the request path

func StringParams

func StringParams(params map[string]string) RequestOption

set the request URL parameters

func Trace

func Trace(tracer *httptrace.ClientTrace) RequestOption

set request ClientTrace

func URL

func URL(u *url.URL) RequestOption

set the request URL

func URLString

func URLString(ustring string) RequestOption

set the request URL (passed as string)

type RequestTrace

type RequestTrace struct {
	DNS          time.Duration
	Connect      time.Duration
	Connected    bool
	TLSHandshake time.Duration
	Request      time.Duration
	Wait         time.Duration
	Response     time.Duration

	Local  string
	Remote string
	// contains filtered or unexported fields
}

func (*RequestTrace) Done

func (r *RequestTrace) Done()

func (*RequestTrace) NewClientTrace

func (r *RequestTrace) NewClientTrace(trace bool) *httptrace.ClientTrace

func (*RequestTrace) Reset

func (r *RequestTrace) Reset()

func (*RequestTrace) String

func (r *RequestTrace) String() string

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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