go_requests

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Jan 10, 2023 License: MIT Imports: 14 Imported by: 0

README ΒΆ

go-requests an HTTP client for Go


An HTTP client that is ready for production in Go for a lot of useful features while only using the standard library of the language.

Installation

To use the library for HTTP calls, you must first import the corresponding HTTP package:

go get github.com/cploutarchou/go-requests

Usage

Client
  1. Create a new client with the default configuration
	builder := requests.NewBuilder()
	client := builder.Build()
  1. Create a new client with a custom configuration
	builder := requests.NewBuilder()
	
	builder.Headers().
		SetContentType("application/json").
        SetAccept("application/json").
        SetUserAgent("go-requests")
        builder.SetRequestTimeout(10 * time.Second).
        SetResponseTimeout(10 * time.Second).
        SetMaxIdleConnections(10)
	client := builder.Build()
  1. Create a new client with our own http.Client
	customClient := &http.Client{
	Timeout: 10 * time.Second, 
	Transport: &http.Transport{
		MaxIdleConnsPerHost:   10, 
		ResponseHeaderTimeout: 10 * time.Second, 
		DialContext: (&net.Dialer{
			Timeout: 10 * time.Second,
		}).DialContext,
	},
	}
	builder := requests.NewBuilder()
	builder.Headers().
		SetContentType("application/json").
		SetAccept("application/json").SetUserAgent("go-requests")
	builder.SetHTTPClient(customClient)
	client := builder.Build()

Requests
GET
    type PetTag struct {
	    PhotoUrls []string `json:"photoUrls"`
	    Name      string   `json:"name"`
	    ID        int64    `json:"id"`
	    Category  struct {
		    Name string `json:"name"`
		    ID   int64  `json:"id"`
	    } `json:"category"`
	    Tags []struct {
		    Name string `json:"name"`
		    ID   int64  `json:"id"`
	    } `json:"tags"`
	    Status string `json:"status"`
	}

	type PetsTags []PetTag
        tags := "dogs,cats"
	
	client.QueryParams().Set("tags", tags)
	resp, err := jsonContentClient.Get("https://request-url.com/pet/findByTags")
	if err != nil {
		fmt.Println(err)
	}
	var pets PetsTags
	// Unmarshal the response body into the struct we support the JSON, XML, YAML,Text formats
	err = resp.Unmarshal(&pets)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(string(pets))

For more examples, see the examples directory.

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. Please make sure to update tests as appropriate.

License

MIT

πŸ’° You can help me by Donating

BuyMeACoffee PayPal Ko-Fi

Thanks for your support! πŸ™

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

This section is empty.

Functions ΒΆ

This section is empty.

Types ΒΆ

type Authorization ΒΆ

type Authorization interface {
	//	Basic sets the authorization to basic
	Bearer(token string) Authorization

	// Basic sets the authorization to basic
	Basic(username, password string) Authorization

	// String returns the string representation of the authorization
	String() string

	// Type returns the type of the authorization
	Type() AuthorizationType

	// Value returns the value of the authorization
	Value() string

	// IsBasic returns true if the authorization is basic
	IsBasic() bool

	// IsBearer returns true if the authorization is bearer
	IsBearer() bool

	// IsEmpty returns true if the authorization is empty
	IsEmpty() bool

	// IsSet returns true if the authorization is set
	IsSet() bool
}

func NewAuthorization ΒΆ

func NewAuthorization() Authorization

NewAuthorization creates a new authorization

type AuthorizationType ΒΆ

type AuthorizationType string

AuthorizationType is the type of the authorization header value

const (
	//AuthorizationTypeBasic is the basic authorization type
	AuthorizationTypeBasic AuthorizationType = "Basic"
	//AuthorizationTypeBearer is the bearer authorization type
	AuthorizationTypeBearer AuthorizationType = "Bearer"
)

type Builder ΒΆ

type Builder interface {
	//SetRequestTimeout sets the timeout for the HTTP request.
	SetRequestTimeout(timeout time.Duration) Timeout
	//SetResponseTimeout sets the timeout for the HTTP response.
	SetResponseTimeout(timeout time.Duration) Timeout
	//SetMaxIdleConnections sets the maximum number of idle (keep-alive) connections across all hosts.
	SetMaxIdleConnections(maxConnections int) Timeout
	//Headers returns the Headers object that is used to set the headers for the HTTP request.
	Headers() Headers
	//Build returns a Client that is used to make HTTP requests.
	Build() Client
	//SetHTTPClient sets the http client to be used for the request instead of the default one.
	SetHTTPClient(*http.Client)
}

Builder is the interface that wraps the basic Build method. The Build method returns a Client. The Client is used to make HTTP requests.

func NewBuilder ΒΆ

func NewBuilder() Builder

NewBuilder returns a new Builder. The Builder is used to build a client with the desired configuration.

type Client ΒΆ

type Client interface {
	QueryParams() QueryParams
	DisableTimeouts()
	EnableTimeouts()
	Headers() Headers

	Get(url string, headers ...http.Header) (*Response, error)
	Post(url string, body []byte, headers ...http.Header) (*Response, error)
	Put(url string, body []byte, headers ...http.Header) (*Response, error)
	Patch(url string, body []byte, headers ...http.Header) (*Response, error)
	Delete(url string, body []byte, headers ...http.Header) (*Response, error)
	Head(url string, body []byte, headers ...http.Header) (*Response, error)
}

Client is an interface for http client

type ContentType ΒΆ

type ContentType string

ContentType of the response to determine the unmarshal method.

type ErrorContentType ΒΆ

type ErrorContentType error

ErrorContentType is the error type for content type errors

func NoContentType ΒΆ

func NoContentType() ErrorContentType

NoContentType is the error type for no content type errors. It is returned when the content type is not set. This is the default error type.

func UnsupportedContentType ΒΆ

func UnsupportedContentType() ErrorContentType

UnsupportedContentType is the error type for unsupported content type errors. It is returned when the content type is not supported by the library.

type HeaderType ΒΆ

type HeaderType string

HeaderType is the type of the header. It is used to set the header value to the header object using the Set method.

const (
	//HeaderTypeAccept is the Accept header
	HeaderTypeAccept HeaderType = "Accept"
	//HeaderTypeAcceptCharset is the Accept-Charset header
	HeaderTypeAcceptCharset HeaderType = "Accept-Charset"
	//HeaderTypeAcceptEncoding is the Accept-Encoding header
	HeaderTypeAcceptEncoding HeaderType = "Accept-Encoding"
	//HeaderTypeAcceptLanguage is the Accept-Language header
	HeaderTypeAcceptLanguage HeaderType = "Accept-Language"
	//HeaderTypeAcceptRanges is the Accept-Ranges header
	HeaderTypeAcceptRanges HeaderType = "Accept-Ranges"
	//HeaderTypeAge is the Age header
	HeaderTypeAge HeaderType = "Age"
	//HeaderTypeAllow is the Allow header
	HeaderTypeAllow HeaderType = "Allow"
	//HeaderTypeContentDisposition is the Content-Disposition header
	HeaderTypeContentDisposition HeaderType = "Content-Disposition"
	//HeaderTypeContentEncoding is the Content-Encoding header
	HeaderTypeContentEncoding HeaderType = "Content-Encoding"
	//HeaderTypeContentLanguage is the Content-Language header
	HeaderTypeContentLanguage HeaderType = "Content-Language"
	//HeaderTypeContentLength is the Content-Length header
	HeaderTypeContentLength HeaderType = "Content-Length"
	//HeaderTypeContentLocation is the Content-Location header
	HeaderTypeContentLocation HeaderType = "Content-Location"
	//HeaderTypeContentMD5 is the Content-MD5 header
	HeaderTypeContentMD5 HeaderType = "Content-MD5"
	//HeaderTypeContentRange is the Content-Range header
	HeaderTypeContentRange HeaderType = "Content-Range"
	//HeaderTypeContentType is the Content-Type header
	HeaderTypeContentType HeaderType = "Content-Type"
	//HeaderTypeCookie is the Cookie header
	HeaderTypeCookie HeaderType = "Cookie"
	//HeaderTypeDate is the Date header
	HeaderTypeDate HeaderType = "Date"
	//HeaderTypeETag is the ETag header
	HeaderTypeETag HeaderType = "ETag"
	//HeaderTypeExpires is the Expires header
	HeaderTypeExpires HeaderType = "Expires"
)

type Headers ΒΆ

type Headers interface {
	// Set sets a header to the header
	Set(key, value string) Headers
	// SetContentType sets the content type to the header
	SetContentType(contentType string) Headers
	// SetContentLength sets the content length to the header
	SetContentLength(contentLength int) Headers
	// SetContentDisposition sets the content disposition to the header
	SetContentDisposition(contentDisposition string) Headers
	// SetContentEncoding sets the content encoding to the header
	SetContentEncoding(contentEncoding string) Headers
	// SetContentLanguage sets the content language to the header
	SetContentLanguage(contentLanguage string) Headers
	// SetContentLocation sets the content location to the header
	SetContentLocation(contentLocation string) Headers
	// SetContentMD5 sets the content md5 to the header
	SetContentMD5(contentMD5 string) Headers
	// SetContentRange sets the content range to the header
	SetContentRange(contentRange string) Headers
	// SetCookie sets the cookie to the header
	SetCookie(cookie string) Headers
	// SetDate sets the date to the header
	SetDate(date string) Headers
	// SetETag sets the etag to the header
	SetETag(etag string) Headers
	// SetExpires sets the expires to the header
	SetExpires(expires string) Headers
	// SetAccept sets to accept to the header
	SetAccept(accept string) Headers
	// SetAcceptCharset sets to accept charset to the header
	SetAcceptCharset(acceptCharset string) Headers
	// SetAcceptEncoding sets to accept encoding to the header
	SetAcceptEncoding(acceptEncoding string) Headers
	// SetAcceptLanguage sets to accept language to the header
	SetAcceptLanguage(acceptLanguage string) Headers
	// SetAcceptRanges sets to accept ranges to the header
	SetAcceptRanges(acceptRanges string) Headers
	// SetAge sets the age to the header
	SetAge(age string) Headers
	// SetAllow sets to allow to the header
	SetAllow(allow string) Headers
	// SetCustom sets a custom header to the header
	SetCustom(key, value string) Headers
	// Get returns the value of the header
	Get(key string) string
	// Del deletes a header from the header
	Del(key string) Headers
	// Clone returns a clone of the header
	Clone() Headers
	// IsEmpty returns true if the header is empty
	IsEmpty() bool
	// IsSet returns true if the header is set
	IsSet() bool
	// String returns the string representation of the header
	String() string
	// Values returns the values of the header
	Values() map[string]string
	// Keys returns the keys of the header
	Keys() []string
	// Len returns the length of the header
	Len() int
	// GetAll returns all Headers with key and value
	GetAll() map[string][]string
	//GetAllHttpHeaders returns all http headers as http.Header object
	GetAllHttpHeaders() http.Header
	//SetUserAgent sets the user agent to the header.
	SetUserAgent(userAgent string)
}

Headers is the interface for the http headers object of the http package of the standard library of Go (golang)

func NewHeaders ΒΆ

func NewHeaders() Headers

NewHeaders returns a new header object

type Method ΒΆ

type Method string

type QueryParams ΒΆ

type QueryParams interface {
	// Add adds the key, value pair to the query params.
	// If the key already exists, the value will be appended to the existing values.
	Add(key, value string) QueryParams
	// Set sets the key, value pair to the query params.
	// If the key already exists, the value will be replaced with the new value.
	Set(key, value string) QueryParams
	// Get gets the first value associated with the given key.
	// If there are no values associated with the key, Get returns "".
	// To access multiple values, use the map directly.
	Get(key string) string
	// Del deletes the values associated with key.
	Del(key string) QueryParams
	// Values returns the values map.
	Values() map[string]string
	// Clone returns a copy of the QueryParams.
	Clone() QueryParams
	// Reset resets the QueryParams to the initial state.
	Reset() QueryParams
	// Len returns the number of query params.
	Len() int
}

QueryParams is the interface for query params. It is used to add, set, get, delete and clone query params.

func NewQueryParams ΒΆ

func NewQueryParams() QueryParams

NewQueryParams returns a new QueryParams. It is used to add, set, get, delete and clone query params.

type Response ΒΆ

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

Response is the struct that holds the response of the HTTP request.

  • It contains the HTTP status code, HTTP header, HTTP status, and response body.
  • The response body is in []byte format.
  • The response body can be unmarshaled into a struct using the unmarshalJSON, unmarshalXML, or UnmarshalYAML methods.
  • The response body can be converted into a string using the String method.
  • The response body can be converted into a []byte using the Body method.
  • The HTTP status code can be retrieved using the StatusCode method.
  • The HTTP header can be retrieved using the Header method.
  • The HTTP status can be retrieved using the Status method.

func (*Response) Bytes ΒΆ

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

Bytes returns the response body in []byte format.

func (*Response) ContentType ΒΆ

func (r *Response) ContentType() ContentType

func (*Response) Header ΒΆ

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

Header returns the HTTP header of the response.

func (*Response) Status ΒΆ

func (r *Response) Status() string

Status returns the HTTP status of the response.

func (*Response) StatusCode ΒΆ

func (r *Response) StatusCode() int

StatusCode returns the HTTP status code of the response.

func (*Response) String ΒΆ

func (r *Response) String() string

String returns a response body in string format.

func (*Response) Unmarshal ΒΆ

func (r *Response) Unmarshal(v interface{}) ErrorContentType

Unmarshal the response body into the given interface.

  • It uses the content-type of the response to determine the unmarshal method.
  • It supports json, xml, and yaml.
  • It returns an error if the content-type is not supported.
  • It returns an error if the unmarshal method fails.
  • It returns an error if the given interface is not a pointer.

func (*Response) UnmarshalYAML ΒΆ

func (r *Response) UnmarshalYAML(v interface{}) error

UnmarshalYAML unmarshal the response body into the given interface.

type Timeout ΒΆ

type Timeout interface {
	// SetRequestTimeout sets the request Timeout
	// if the value is 0, the request will not Timeout.
	//	Example:
	//		client.SetRequestTimeout(10 * time.Second)
	//		client.SetRequestTimeout(0)
	SetRequestTimeout(time.Duration) Timeout
	// SetResponseTimeout sets the response Timeout
	// if the value is 0, the response will not Timeout.
	//	Example:
	//		client.SetResponseTimeout(10 * time.Second)
	//		client.SetResponseTimeout(0)
	SetResponseTimeout(time.Duration) Timeout
	// SetMaxIdleConnections sets the maximum number of idle connections
	// if the value is 0, the maximum number of idle connections will be set to 10
	//	Example:
	//		client.SetMaxIdleConnections(10)
	//		client.SetMaxIdleConnections(0)
	SetMaxIdleConnections(int) Timeout
	// GetMaxIdleConnections returns the maximum number of idle connections
	// if the value is not set, it returns the default value.
	// default value is 10
	//	Example:
	//		client.GetMaxIdleConnections()
	GetMaxIdleConnections() int
	// GetRequestTimeout returns the request Timeout
	// if the request Timeout is not set, it returns the default request Timeout.
	//	Example:
	//		client.GetRequestTimeout()
	GetRequestTimeout() time.Duration
	// GetResponseTimeout returns the response Timeout
	// if the request Timeout is not set, it returns the default response Timeout
	//	Example:
	//		client.GetResponseTimeout()
	GetResponseTimeout() time.Duration
	// Disable disables the Timeout
	//	Example:
	//		client.Disable()
	Disable() Timeout
	// Enable enables the Timeout
	//	Example:
	//		client.Enable()
	Enable() Timeout
}

Timeout is an interface that holds the configuration for the http client.

Directories ΒΆ

Path Synopsis

Jump to

Keyboard shortcuts

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