request

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2021 License: MIT Imports: 17 Imported by: 2

README

Go Reference codecov

Client request abstraction

Simple abstraction for client requests with memory cache.

Initialize the client:

import "github.com/Pantani/request"

client := request.InitClient("http://127.0.0.1:8080")
// OR
client := request.Request{
	HttpClient:   request.DefaultClient,
	ErrorHandler: request.DefaultErrorHandler,
	BaseUrl:      "http://127.0.0.1:8080",
	Headers: map[string]string{
		"Content-Type": "application/json",
		"Accept":       "application/json",
	},
}

Methods

GET
var result CustomResult
err := client.Get(&result, "api/v1/object", url.Values{"id": {"69"}})

// with cache
err := request.GetWithCache(&result, "api/v1/object", url.Values{"id": {"69"}}, time.Hour*1)
POST
var result CustomResult
err := client.Post(&result, "api/v1/object", Request{Name: "name", Id: "id"})

// with cache
err := request.PostWithCache(&result, "api/v1/object", Request{Name: "name", Id: "id"}, time.Hour*1)

Parameters

  • Add Error Handler:
client.ErrorHandler = func(res *http.Response, desc string) error {
	switch res.StatusCode {
	case http.StatusBadRequest:
		return getAPIError(res, desc)
	case http.StatusNotFound:
		return blockatlas.ErrNotFound
	case http.StatusOK:
		return nil
	default:
		return errors.E("getHTTPError error", errors.Params{"status": res.Status})
	}
}
  • Set timeout:
client.SetTimeout(35)
  • Add header:
client.Headers["X-API-KEY"] = "<API_KEY>"

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultClient = &http.Client{
	Timeout: time.Second * 15,
}

DefaultClient represents a generic and default http client.

View Source
var DefaultErrorHandler = func(res *http.Response, uri string) error {
	return nil
}

DefaultErrorHandler represents a generic and default error handler.

Functions

func GetBody

func GetBody(body interface{}) (buf io.ReadWriter, err error)

GetBody cast custom object body to io.ReadWriter buffer It returns an error if occurs.

Types

type Request

type Request struct {
	BaseURL      string
	Headers      map[string]string
	HTTPClient   *http.Client
	ErrorHandler func(res *http.Response, uri string) error
}

Request object

func InitClient

func InitClient(baseURL string) Request

InitClient initialize the client request.

func InitJSONClient

func InitJSONClient(baseURL string) Request

InitJSONClient initialize the client for application/json requests.

func (*Request) Execute

func (r *Request) Execute(ctx context.Context, method string, url string, body io.Reader, result interface{}) error

Execute sends any HTTP request and returns an HTTP response, following policy (such as redirects, cookies, auth) as configured on the client. The response is unmarshal and stored inside the result parameter.

An error is returned if caused by client policy (such as CheckRedirect), or failure to speak HTTP (such as a network connectivity problem). A non-2xx status code doesn't cause an error.

eg.:

var block Block
err := r.Execute("POST", uri, buf, result)

func (*Request) Get

func (r *Request) Get(result interface{}, path string, query url.Values) error

Get sends an HTTP GET request and returns an HTTP response in background context, following policy (such as redirects, cookies, auth) as configured on the client.

The response is unmarshal and stored inside the result parameter.

An error is returned if caused by client policy (such as CheckRedirect), or failure to speak HTTP (such as a network connectivity problem). A non-2xx status code doesn't cause an error.

eg.:

var block Block
err := c.Get(&block, "blocks/latest", url.Values{"page": {"1"}})

func (*Request) GetBase

func (r *Request) GetBase(path string) string

GetBase returns the base url with path.

func (*Request) GetWithCache

func (r *Request) GetWithCache(result interface{}, path string, query url.Values, cache time.Duration) error

GetWithCache sends an HTTP GET request with cache duration. After the duration the cache is expires and the request are made again. It returns an error if occurs.

eg.:

var block Block
err := c.Get(&block, "blocks/latest", url.Values{"page": {"1"}}, time.Minute*20)

func (*Request) GetWithContext

func (r *Request) GetWithContext(ctx context.Context, result interface{}, path string, query url.Values) error

GetWithContext sends an HTTP GET request and returns an HTTP response in the passed context, following policy (such as redirects, cookies, auth) as configured on the client.

The response is unmarshal and stored inside the result parameter.

An error is returned if caused by client policy (such as CheckRedirect), or failure to speak HTTP (such as a network connectivity problem). A non-2xx status code doesn't cause an error.

eg.:

var block Block
err := c.GetWithContext(&block, "blocks/latest", url.Values{"page": {"1"}}, context.Background())

func (*Request) Post

func (r *Request) Post(result interface{}, path string, body interface{}) error

Post sends an HTTP POST request and returns an HTTP response in background context, following policy (such as redirects, cookies, auth) as configured on the client.

The response is unmarshal and stored inside the result parameter.

An error is returned if caused by client policy (such as CheckRedirect), or failure to speak HTTP (such as a network connectivity problem). A non-2xx status code doesn't cause an error.

eg.:

var block Block
err := c.Post(&block, "blocks/latest", CustomObject{Id: 3, Name: "request"})

func (*Request) PostWithCache

func (r *Request) PostWithCache(result interface{}, path string, body interface{}, cache time.Duration) error

PostWithCache sends an HTTP POST request with cache duration. After the duration the cache is expires and the request are made again. It returns an error if occurs.

eg.:

var block Block
err := c.PostWithCache(&block, "blocks/latest", CustomObject{Id: 3, Name: "request"}, time.Minute*20)

func (*Request) PostWithContext

func (r *Request) PostWithContext(ctx context.Context, result interface{}, path string, body interface{}) error

PostWithContext sends an HTTP POST request and returns an HTTP response in the passed context, following policy (such as redirects, cookies, auth) as configured on the client.

The response is unmarshal and stored inside the result parameter.

An error is returned if caused by client policy (such as CheckRedirect), or failure to speak HTTP (such as a network connectivity problem). A non-2xx status code doesn't cause an error.

eg.:

var block Block
err := c.PostWithContext(&block, "blocks/latest", CustomObject{Id: 3, Name: "request"}, context.Background())

func (*Request) SetTimeout

func (r *Request) SetTimeout(seconds time.Duration)

SetTimeout set the timeout request.

Jump to

Keyboard shortcuts

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