easyhttp

package module
v1.12.1 Latest Latest
Warning

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

Go to latest
Published: May 6, 2021 License: MIT Imports: 31 Imported by: 12

README

easyhttp

Easy HTTP and REST client library for Go (inspired by Resty)

Features

  • GET, POST, PUT, DELETE, HEAD, PATCH, OPTIONS, etc.
  • Easy to extend via interceptor.
  • Builder Pattern build the request
  • Functional Options Pattern create client
  • Chain of Responsibility Pattern to extend function

Installation

go get -u github.com/soyacen/easyhttp

Requirements

  • Go 1.9+

Middleware

Usage

Simple GET
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/soyacen/easyhttp"
)

type Body struct {
	Args struct {
	} `json:"args"`
	Headers struct {
		AcceptEncoding string `json:"Accept-Encoding"`
		Host           string `json:"Host"`
		UserAgent      string `json:"User-Agent"`
		XAmznTraceId   string `json:"X-Amzn-Trace-Id"`
	} `json:"headers"`
	Origin string `json:"origin"`
	Url    string `json:"url"`
}

func main() {
	client := easyhttp.NewClient(
		easyhttp.ChainInterceptor(
			func(cli *easyhttp.Client, req *easyhttp.Request, resp *easyhttp.Response, do easyhttp.Doer) error {
				log.Println("enter interceptor 1")
				defer log.Println("exit interceptor 1")
				return do(cli, req, resp)
			},
			func(cli *easyhttp.Client, req *easyhttp.Request, resp *easyhttp.Response, do easyhttp.Doer) error {
				log.Println("enter interceptor 2")
				defer log.Println("exit interceptor 2")
				return do(cli, req, resp)
			},
		),
	)
	
	result := &Body{}
	builder := easyhttp.NewBuilder(context.Background()).
		URL("http://httpbin.org/get").
		GET().
		Result(result)
	request, response := builder.Build()
	err := client.Execute(request, response)
	if err != nil {
		fmt.Printf("\nError: %v", err)
		return
	}
	fmt.Printf("\nResponse Status Code: %v", response.RawResponse().StatusCode)
	fmt.Printf("\nResponse Status: %v", response.RawResponse().Status)
	fmt.Printf("\nResponse Header: %v", response.RawResponse().Header)
	fmt.Printf("\nResponse Body: %s", response.Content())
	fmt.Printf("\nResult: %v", result)
}

Documentation

Index

Constants

View Source
const (
	MIMEJSON              = "application/json"
	MIMEHTML              = "text/html"
	MIMEXML               = "application/xml"
	MIMEXML2              = "text/xml"
	MIMEPlain             = "text/plain"
	MIMEPOSTForm          = "application/x-www-form-urlencoded"
	MIMEMultipartPOSTForm = "multipart/form-data"
	MIMEPROTOBUF          = "application/x-protobuf"
	MIMEMSGPACK           = "application/x-msgpack"
	MIMEMSGPACK2          = "application/msgpack"
	MIMEYAML              = "application/x-yaml"
)

Content-Type MIME of the most common data formats.

Variables

This section is empty.

Functions

func DetectContentType added in v1.12.1

func DetectContentType(body interface{}) string

DetectContentType method is used to figure out `Request.Body` content type for request header

func IsJSONType added in v1.12.1

func IsJSONType(ct string) bool

IsJSONType method is to check JSON content type or not

func IsProtobufType added in v1.12.1

func IsProtobufType(ct string) bool

IsProtobufType method is to check Protocol Buffers content type or not

func IsStringEmpty added in v1.12.1

func IsStringEmpty(str string) bool

IsStringEmpty method tells whether given string is empty or not

func IsXMLType added in v1.12.1

func IsXMLType(ct string) bool

IsXMLType method is to check XML content type or not

func IsYAMLType added in v1.12.1

func IsYAMLType(ct string) bool

IsYAMLType method is to check YAML content type or not

func Unmarshalc added in v1.12.1

func Unmarshalc(c *Client, ct string, b []byte, d interface{}) (err error)

Unmarshalc content into object from JSON or XML

Types

type Builder added in v1.12.1

type Builder struct {
	Request  *Request
	Response *Response
	// contains filtered or unexported fields
}

func NewBuilder added in v1.12.1

func NewBuilder(ctx context.Context) *Builder

func (*Builder) AddHeader added in v1.12.1

func (builder *Builder) AddHeader(key, value string) *Builder

func (*Builder) AddHeaders added in v1.12.1

func (builder *Builder) AddHeaders(headers map[string]string) *Builder

func (*Builder) Body added in v1.12.1

func (builder *Builder) Body(body io.Reader) *Builder

func (*Builder) Build added in v1.12.1

func (builder *Builder) Build() (*Request, *Response)

func (*Builder) CONNECT added in v1.12.1

func (builder *Builder) CONNECT() *Builder

func (*Builder) Client added in v1.12.1

func (builder *Builder) Client(cli *Client) *Builder

func (*Builder) ContentType added in v1.12.1

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

func (*Builder) Context added in v1.12.1

func (builder *Builder) Context(ctx context.Context) *Builder

func (*Builder) DELETE added in v1.12.1

func (builder *Builder) DELETE() *Builder

func (*Builder) EnableJSONEscapeHTML added in v1.12.1

func (builder *Builder) EnableJSONEscapeHTML(enabled bool) *Builder

func (*Builder) ErrorResult added in v1.12.1

func (builder *Builder) ErrorResult(result interface{}) *Builder

func (*Builder) File added in v1.12.1

func (builder *Builder) File(paramName ParamName, filePath FilePath) *Builder

func (*Builder) FileReader added in v1.12.1

func (builder *Builder) FileReader(paramName ParamName, fileName Filename, reader io.Reader) *Builder

func (*Builder) GET added in v1.12.1

func (builder *Builder) GET() *Builder

func (*Builder) HEAD added in v1.12.1

func (builder *Builder) HEAD() *Builder

func (*Builder) Header added in v1.12.1

func (builder *Builder) Header(header http.Header) *Builder

func (*Builder) MultipartField added in v1.12.1

func (builder *Builder) MultipartField(param ParamName, fileName Filename, contentType string, reader io.Reader) *Builder

func (*Builder) MultipartFormData added in v1.12.1

func (builder *Builder) MultipartFormData(data map[ParamName]io.Reader) *Builder

func (*Builder) OPTIONS added in v1.12.1

func (builder *Builder) OPTIONS() *Builder

func (*Builder) PATCH added in v1.12.1

func (builder *Builder) PATCH() *Builder

func (*Builder) POST added in v1.12.1

func (builder *Builder) POST() *Builder

func (*Builder) PUT added in v1.12.1

func (builder *Builder) PUT() *Builder

func (*Builder) PathParam added in v1.12.1

func (builder *Builder) PathParam(param, value string) *Builder

func (*Builder) PathParams added in v1.12.1

func (builder *Builder) PathParams(params map[string]string) *Builder

func (*Builder) QueryParam added in v1.12.1

func (builder *Builder) QueryParam(param, value string) *Builder

func (*Builder) QueryParams added in v1.12.1

func (builder *Builder) QueryParams(params map[string]string) *Builder

func (*Builder) Result added in v1.12.1

func (builder *Builder) Result(result interface{}) *Builder

func (*Builder) SetFiles added in v1.12.1

func (builder *Builder) SetFiles(files map[ParamName]FilePath) *Builder

func (*Builder) SetHeader added in v1.12.1

func (builder *Builder) SetHeader(key, value string) *Builder

func (*Builder) SetHeaders added in v1.12.1

func (builder *Builder) SetHeaders(headers map[string]string) *Builder

func (*Builder) SetMultipartFields added in v1.12.1

func (builder *Builder) SetMultipartFields(fields ...*MultipartField) *Builder

func (*Builder) TRACE added in v1.12.1

func (builder *Builder) TRACE() *Builder

func (*Builder) URL added in v1.12.1

func (builder *Builder) URL(url string) *Builder

type Client

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

func NewClient

func NewClient(opts ...Option) *Client

func (*Client) Execute

func (cli *Client) Execute(req *Request, resp *Response) (err error)

func (*Client) GetClient added in v1.12.1

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

GetClient method returns the current `http.Client` used by the client.

func (*Client) IsProxySet added in v1.12.1

func (c *Client) IsProxySet() bool

IsProxySet method returns the true is proxy is set from resty client otherwise false. By default proxy is set from environment, refer to `http.ProxyFromEnvironment`.

func (*Client) RawClient

func (cli *Client) RawClient() *http.Client

func (*Client) RemoveProxy added in v1.12.1

func (c *Client) RemoveProxy() (*Client, error)

RemoveProxy method removes the proxy configuration from Resty client

client.RemoveProxy()

func (*Client) SetCertificates added in v1.12.1

func (c *Client) SetCertificates(certs ...tls.Certificate) (*Client, error)

SetCertificates method helps to set client certificates into Resty conveniently.

func (*Client) SetRootCertificate added in v1.12.1

func (c *Client) SetRootCertificate(pemFilePath string) (*Client, error)

SetRootCertificate method helps to add one or more root certificates into Resty client

client.SetRootCertificate("/path/to/root/pemFile.pem")

func (*Client) SetRootCertificateFromString added in v1.12.1

func (c *Client) SetRootCertificateFromString(pemContent string) (*Client, error)

SetRootCertificateFromString method helps to add one or more root certificates into Resty client

client.SetRootCertificateFromString("pem file content")

type Doer

type Doer func(cli *Client, req *Request, resp *Response) error

type File added in v1.12.1

type File struct {
	io.Reader
	// contains filtered or unexported fields
}

File struct represent file information for multipart request

func (*File) String added in v1.12.1

func (f *File) String() string

MultipartField returns string value of current file details

type FilePath added in v1.12.1

type FilePath = string

type Filename added in v1.12.1

type Filename = string

type Interceptor

type Interceptor func(cli *Client, req *Request, resp *Response, do Doer) error

type MultipartField added in v1.12.1

type MultipartField struct {
	io.Reader
	// contains filtered or unexported fields
}

MultipartField struct represent custom data part for multipart request

func NewMultipartField added in v1.12.1

func NewMultipartField(param ParamName, fileName Filename, contentType string, reader io.Reader) *MultipartField

type Option added in v1.12.1

type Option func(o *options)

func AddHeader added in v1.12.1

func AddHeader(key, value string) Option

func AddHeaders added in v1.12.1

func AddHeaders(headers map[string]string) Option

func AuthScheme added in v1.12.1

func AuthScheme(scheme string) Option

func AuthToken added in v1.12.1

func AuthToken(token string) Option

func BasicAuth added in v1.12.1

func BasicAuth(username, password string) Option

func ChainInterceptor

func ChainInterceptor(interceptors ...Interceptor) Option

func CheckRedirect added in v1.12.1

func CheckRedirect(policies ...RedirectPolicy) Option
func Cookie(hc *http.Cookie) Option

func CookieJar added in v1.12.1

func CookieJar(jar http.CookieJar) Option

func Cookies added in v1.12.1

func Cookies(cs []*http.Cookie) Option

func DoNotParseResponse added in v1.12.1

func DoNotParseResponse(parse bool) Option

func EnableCloseConnection added in v1.12.1

func EnableCloseConnection(enabled bool) Option

func EnableJSONEscapeHTML added in v1.12.1

func EnableJSONEscapeHTML(enabled bool) Option

func FormData added in v1.12.1

func FormData(data map[string]string) Option
func Header(header http.Header) Option

func HostURL added in v1.12.1

func HostURL(url string) Option

func PathParam added in v1.12.1

func PathParam(param, value string) Option

func PathParams added in v1.12.1

func PathParams(params map[string]string) Option

func Proxy added in v1.12.1

func Proxy(proxyURL string) Option

func QueryParam added in v1.12.1

func QueryParam(param, value string) Option

func QueryParams added in v1.12.1

func QueryParams(params map[string]string) Option

func Scheme added in v1.12.1

func Scheme(scheme string) Option

func SetHeader added in v1.12.1

func SetHeader(key, value string) Option

func SetHeaders added in v1.12.1

func SetHeaders(headers map[string]string) Option

func SetOutputDirectory added in v1.12.1

func SetOutputDirectory(dirPath string) Option

func TLSConfig added in v1.12.1

func TLSConfig(config *tls.Config) Option

func Timeout added in v1.12.1

func Timeout(timeout time.Duration) Option

func Transport added in v1.12.1

func Transport(transport http.RoundTripper) Option

type ParamName added in v1.12.1

type ParamName = string

type RedirectPolicy added in v1.12.1

type RedirectPolicy interface {
	Apply(req *http.Request, via []*http.Request) error
}

RedirectPolicy to regulate the redirects in the resty client. Objects implementing the RedirectPolicy interface can be registered as

Apply function should return nil to continue the redirect jounery, otherwise return error to stop the redirect.

func DomainCheckRedirectPolicy added in v1.12.1

func DomainCheckRedirectPolicy(hostnames ...string) RedirectPolicy

DomainCheckRedirectPolicy is convenient method to define domain name redirect rule in resty client. Redirect is allowed for only mentioned host in the policy.

resty.SetRedirectPolicy(DomainCheckRedirectPolicy("host1.com", "host2.org", "host3.net"))

func FlexibleRedirectPolicy added in v1.12.1

func FlexibleRedirectPolicy(noOfRedirect int) RedirectPolicy

FlexibleRedirectPolicy is convenient method to create No of redirect policy for HTTP client.

resty.SetRedirectPolicy(FlexibleRedirectPolicy(20))

func NoRedirectPolicy added in v1.12.1

func NoRedirectPolicy() RedirectPolicy

NoRedirectPolicy is used to disable redirects in the HTTP client

resty.SetRedirectPolicy(NoRedirectPolicy())

type RedirectPolicyFunc added in v1.12.1

type RedirectPolicyFunc func(*http.Request, []*http.Request) error

The RedirectPolicyFunc type is an adapter to allow the use of ordinary functions as RedirectPolicy. If f is a function with the appropriate signature, RedirectPolicyFunc(f) is a RedirectPolicy object that calls f.

func (RedirectPolicyFunc) Apply added in v1.12.1

func (f RedirectPolicyFunc) Apply(req *http.Request, via []*http.Request) error

Apply calls f(req, via).

type Request

type Request struct {
	FormData url.Values

	url.Values
	// contains filtered or unexported fields
}

func (*Request) Body added in v1.12.1

func (r *Request) Body() interface{}

func (*Request) ContentType added in v1.12.1

func (r *Request) ContentType() string

func (*Request) Ctx added in v1.12.1

func (r *Request) Ctx() context.Context

func (*Request) Err added in v1.12.1

func (r *Request) Err() error

func (*Request) Header added in v1.12.1

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

func (*Request) Method added in v1.12.1

func (r *Request) Method() string

func (*Request) RawRequest

func (r *Request) RawRequest() *http.Request

func (*Request) Url added in v1.12.1

func (r *Request) Url() string

func (*Request) WithRawRequest added in v1.12.1

func (r *Request) WithRawRequest(req *http.Request) *Request

type Response added in v1.12.1

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

func (*Response) Content added in v1.12.1

func (r *Response) Content() []byte

func (*Response) IsError added in v1.12.1

func (r *Response) IsError() bool

IsError method returns true if HTTP status `code >= 400` otherwise false.

func (*Response) IsSuccess added in v1.12.1

func (r *Response) IsSuccess() bool

IsSuccess method returns true if HTTP status `code >= 200 and <= 299` otherwise false.

func (*Response) RawResponse added in v1.12.1

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

func (*Response) Result added in v1.12.1

func (r *Response) Result() interface{}

type User added in v1.12.1

type User struct {
	Username, Password string
}

Directories

Path Synopsis
xml
interceptor
auth Module
header Module
logging Module
opentracing Module
reqbody Module
respbody Module
retry Module

Jump to

Keyboard shortcuts

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