request

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2023 License: MIT Imports: 15 Imported by: 0

README

HTTP Request tool for Go

test codecov Version Badge License Badge Go Reference

English | 简体中文

An easy-to-use HTTP request tool for Golang.

Features

  • Timeouts or self-control context.
  • Serialize request body automatically.
  • Response body deserialization wrapper.
  • Decode the compressed response body automatically.

Installation

This package requires Go 1.18 and later versions.

You can install this package by the following command.

go get -u github.com/ghosind/go-request

Getting Started

The is a minimal example of performing a GET request:

resp, err := request.Request("https://example.com/products/1")
if err != nil {
  // handle error
}
// handle response
POST and other requests

You can perform a POST request with a request config that set the Method field's value to POST.

resp, err := request.Request("https://example.com/products", RequestConfig{
  Method: "POST",
  Body:   map[string]any{
    "title": "Apple",
  },
})
// handle error or response

If the ContentType field in the request config is empty, the body data will serialize to a JSON string default, and it'll also set the Content-Type field value in the request headers to application/json.

You can also use POST method to perform a POST request with the specific body data.

resp, err := request.POST("https://example.com/products", RequestConfig{
  Body: map[string]any{
    "title": "Apple",
  },
})
// handle error or response

We also provided the following methods for performing HTTP requests:

  • DELETE
  • GET
  • HEAD
  • OPTIONS
  • PATCH
  • POST
  • PUT

The above methods will overwrite the Method field in the request config.

Timeouts

All the requests will set timeout to 1-second default, you can set a custom timeout value in milliseconds to a request:

resp, err := request.Request("https://example.com", request.RequestConfig{
  Timeout: 3000, // 3 seconds
})
// handle error or response

You can also set Timeout to request.RequestTimeoutNone to disable the timeout mechanism.

The timeout will be disabled if you set Context in the request config, you need to handle it manually.

Response body handling

We provided ToObject and ToString methods to handle response body. For example, the ToString method will read all data in the response body, and return it that represented in a string value.

content, resp, err := ToString(request.Request("https://example.com/products/1"))
if err != nil {
  // handle error
}
// content: {"id":1,"title":"iPhone9",...
// handle response

The ToObject method will read the content type of response and deserialize the body to the specific type.

type Product struct {
  ID    int    `json:"id"`
  Title string `json:"title"`
}

product, resp, err := ToObject[Product](request.Request("https://example.com/products/1"))
if err != nil {
  // handle error
}
// product: {1 iPhone9}
// handle response

Both ToObject and ToString methods will close the Body of the response after reading all data.

Client Instance

You can create a new client instance with a custom config.

cli := request.New(request.Config{
  BaseURL: "https://example.com/",
})

resp, err := cli.GET("/products/1")
// handle error or response
Client Instance Config
Field Type Description
BaseURL string The base url for all requests that performing by this client instance.
Headers map[string][]string Custom headers to be sent.
MaxRedirects int The maximum number of redirects for this client, default 5.
Parameters map[string][]string Custom query string parameters to be sent.
Timeout int Timeout in milliseconds.
UserAgent string Custom user agent value.
ValidateStatus func(int) bool The function checks whether the status code of the response is valid or not.

Request Config

There are the available config options for performing a request, and all fields are optional.

Field Type Description
Auth *BasicAuthConfig HTTP Basic Auth config.
BaseURL string The base url for this requests.
Body any The request body.
ContentType string The content type of this request. Available options are: "json", and default "json".
Context context.Context Self-control context.
DisableDecompress bool Indicates whether or not disable decompression of the response body automatically.
Headers map[string][]string Custom headers to be sent.
MaxRedirects int The maximum number of redirects for the request, default 5.
Method string HTTP request method, default GET.
Parameters map[string][]string Custom query string parameters to be sent.
Timeout int Timeout in milliseconds.
UserAgent string Custom user agent value.
ValidateStatus func(int) bool The function checks whether the status code of the response is valid or not.

Documentation

Index

Constants

View Source
const (
	// RequestTimeoutDefault is the default timeout for request.
	RequestTimeoutDefault int = 1000
	// RequestTimeoutNoLimit means no timeout limitation.
	RequestTimeoutNoLimit int = -1

	// RequestMaxRedirects is the default maximum number of redirects.
	RequestDefaultMaxRedirects int = 5
	// RequestNoRedirect means it'll never redirect automatically.
	RequestNoRedirects int = -1

	// RequestDefaultUserAgent is the default user agent for all requests that are sent by this
	// package.
	RequestDefaultUserAgent string = "go-request/0.2"
)
View Source
const (
	// RequestContentTypeJSON indicates the request body encodes as a JSON.
	RequestContentTypeJSON string = "json"
)

Variables

View Source
var (
	// ErrInvalidMethod throws when the method of the request is not a valid value.
	ErrInvalidMethod error = errors.New("invalid HTTP method")

	// ErrInvalidResp throws when no valid response for wrapper function.
	ErrInvalidResp error = errors.New("invalid response")

	// ErrNoURL throws when no uri and base url set in the request.
	ErrNoURL error = errors.New("no url")

	// ErrUnsupportedType throws when the content type is unsupported.
	ErrUnsupportedType error = errors.New("unsupported content type")
)

Functions

func DELETE

func DELETE(url string, opt ...RequestOptions) (*http.Response, error)

DELETE performs an HTTP DELETE request to the specific URL with the request options.

func GET

func GET(url string, opt ...RequestOptions) (*http.Response, error)

GET performs an HTTP GET request to the specific URL with the request options.

func HEAD(url string, opt ...RequestOptions) (*http.Response, error)

HEAD performs an HTTP HEAD request to the specific URL with the request options.

func OPTIONS

func OPTIONS(url string, opt ...RequestOptions) (*http.Response, error)

OPTIONS performs an HTTP OPTIONS request to the specific URL with the request options.

func PATCH

func PATCH(url string, opt ...RequestOptions) (*http.Response, error)

PATCH performs an HTTP PATCH request to the specific URL with the request options.

func POST

func POST(url string, opt ...RequestOptions) (*http.Response, error)

POST performs an HTTP POST request to the specific URL with the request options.

func PUT

func PUT(url string, opt ...RequestOptions) (*http.Response, error)

PUT performs an HTTP PUT request to the specific URL with the request options.

func Request

func Request(url string, opts ...RequestOptions) (*http.Response, error)

Request performs an HTTP request to the specific URL with the request options. If no request options are set, it will be sent as an HTTP GET request.

resp, err := request.Request("https://example.com")
if err != nil {
  // Error handling
}
// Response handling

func ToObject

func ToObject[T any](resp *http.Response, err error) (*T, *http.Response, error)

ToObject reads data from the response body and tries to decode it to an object as the parameter type. It'll read the encoding type from the 'Content-Type' field in the response header. The method will close the body of the response that after read.

data, resp, err := request.ToObject[SomeStructType](request.Request("https://example.com"))
if err != nil {
  // Error handling
}
// Data or response handling

func ToString

func ToString(resp *http.Response, err error) (string, *http.Response, error)

ToString reads data from the response body and returns them as a string. The method will close the body of the response that after read.

content, resp, err := request.ToString(request.Request("https://example.com"))
if err != nil {
  // Error handling
}
// Response handling

Types

type BasicAuthConfig added in v0.2.0

type BasicAuthConfig struct {
	// Username indicates the username used for HTTP Basic Auth
	Username string
	// Password indicates the password used for HTTP Basic Auth
	Password string
}

BasicAuthConfig indicates the config of the HTTP Basic Auth that is used for the request.

type Client

type Client struct {
	// BaseURL will be prepended to all request URL unless URL is absolute.
	BaseURL string
	// Headers are custom headers to be sent.
	Headers map[string][]string
	// MaxRedirects defines the maximum number of redirects for this client, default 5.
	MaxRedirects int
	// Parameters are the parameters to be sent.
	Parameters map[string][]string
	// Timeout specifies the time before the request times out.
	Timeout int
	// UserAgent sets the client's User-Agent field in the request header.
	UserAgent string
	// ValidateStatus defines whether the status code of the response is valid or not, and it'll
	// return an error if fails to validate the status code.
	ValidateStatus func(int) bool
	// contains filtered or unexported fields
}

Client is the HTTP requesting client.

func New

func New(config ...Config) *Client

New creates and returns a new Client instance.

cli := request.New(request.Config{
  BaseURL: "https://www.example.com", // the base URL for every request sent by this client
  Timeout: 5000, // the default timeout for this client
  // ...
})

func (*Client) DELETE

func (cli *Client) DELETE(url string, opt ...RequestOptions) (*http.Response, error)

DELETE performs an HTTP DELETE request to the specific URL with the request options and the client config.

func (*Client) GET

func (cli *Client) GET(url string, opt ...RequestOptions) (*http.Response, error)

GET performs an HTTP GET request to the specific URL with the request options and the client config.

func (*Client) HEAD

func (cli *Client) HEAD(url string, opt ...RequestOptions) (*http.Response, error)

HEAD performs an HTTP HEAD request to the specific URL with the request options and the client config.

func (*Client) OPTIONS

func (cli *Client) OPTIONS(url string, opt ...RequestOptions) (*http.Response, error)

OPTIONS performs an HTTP OPTIONS request to the specific URL with the request options and the client config.

func (*Client) PATCH

func (cli *Client) PATCH(url string, opt ...RequestOptions) (*http.Response, error)

PATCH performs an HTTP PATCH request to the specific URL with the request options and the client config.

func (*Client) POST

func (cli *Client) POST(url string, opt ...RequestOptions) (*http.Response, error)

POST performs an HTTP POST request to the specific URL with the request options and the client config.

func (*Client) PUT

func (cli *Client) PUT(url string, opt ...RequestOptions) (*http.Response, error)

PUT performs an HTTP PUT request to the specific URL with the request options and the client config.

func (*Client) Request

func (cli *Client) Request(url string, opt ...RequestOptions) (*http.Response, error)

Request performs an HTTP request to the specific URL with the request options and the client config. If no request options are set, it will be sent as an HTTP GET request.

resp, err := cli.Request("https://example.com")
if err != nil {
  // Error handling
}
// Response handling

type Config

type Config struct {
	// BaseURL will be prepended to all request URL unless URL is absolute.
	BaseURL string
	// Headers are custom headers to be sent, and they'll be overwritten if the
	// same key is presented in the request.
	Headers map[string][]string
	// MaxRedirects defines the maximum number of redirects for this client, default 5.
	MaxRedirects int
	// Parameters are the parameters to be sent for all requests of the client. It will be
	// overwritten if the same key is in the parameters of the request options.
	Parameters map[string][]string
	// Timeout is request timeout in milliseconds.
	Timeout int
	// UserAgent sets the client's User-Agent field in the request header.
	UserAgent string
	// ValidateStatus defines whether the status code of the response is valid or not, and it'll
	// return an error if fails to validate the status code. Default, it sets the result to fail if
	// the status code is less than 200, or greater than and equal to 400.
	//
	//	cli := request.New(request.Config{
	//	  ValidateStatus: func (status int) bool {
	//	    // Only success if the status code of response is 2XX
	//	    return status >= http.StatusOk && status <= http.StatusMultipleChoices
	//	  },
	//	})
	ValidateStatus func(int) bool
}

Config is the config for the HTTP requesting client.

type RequestOptions

type RequestOptions struct {
	// Auth indicates that HTTP Basic auth should be used. It will set an `Authorization` header,
	// and it'll also overwriting any existing `Authorization` field in the request header.
	//
	//	resp, err := request.Request("https://example.com", request.RequestOptions{
	//	  Auth: &request.BasicAuthConfig{
	//	    Username: "user",
	//	    Password: "pass",
	//	  },
	//	})
	Auth *BasicAuthConfig
	// BaseURL will prepended to the url of the request unless the url is absolute.
	//
	//	resp, err := request.Request("/test", request.RequestOptions{
	//	  BaseURL: "http://example.com",
	//	})
	//	// http://example.com/test
	BaseURL string
	// Body is the data to be sent as the request body. It'll be encoded with the content type
	// specified by the `ContentType` field in the request options, or encoded as a JSON if the
	// `ContentType` field is empty. It'll skip the encode processing if the value is a string or a
	// slice of bytes.
	//
	//	resp, err := request.Request("http://example.com", request.RequestOptions{
	//	  Method: http.MethodPost,
	//	  Body: "Hello world!", // with raw string
	//	})
	//
	//	resp, err := request.Request("http://example.com", request.RequestOptions{
	//	  Method: http.MethodPost,
	//	  // with struct/map, and it'll encoding by the value of ContentType field.
	//	  Body: map[string]any{
	//	    "data": "Hello world",
	//	  },
	//	})
	Body any
	// ContentType indicates the type of data that will encode and send to the server. Available
	// options are: "json", default "json".
	//
	//	request.POST("http://example.com", request.RequestOptions{
	//	  ContentType: request.RequestContentTypeJSON, // "json"
	//	  // ...
	//	})
	ContentType string
	// Context is a `context.Content` object that is used for manipulating the request by yourself.
	// The `Timeout` field will be ignored if this value is not empty, and you need to control
	// timeout by yourself.
	//
	//	ctx, canFunc := context.WithTimeout(context.Background(), time.Second)
	//	defer canFunc()
	//	resp, err := request.Request("http://example.com", request.RequestOptions{
	//	  Context: ctx,
	//	})
	Context context.Context
	// DisableDecompress indicates whether or not disable decompression of the response body
	// automatically. If it is set to `true`, it will not decompress the response body.
	DisableDecompress bool
	// Headers are custom headers to be sent.
	//
	//	resp, err := request.Request("http://example.com", request.RequestOptions{
	//	  Headers: map[string][]string{
	//	    "Authorization": {"Bearer XXXXX"},
	//	  },
	//	})
	Headers map[string][]string
	// MaxRedirects defines the maximum number of redirects, default 5.
	MaxRedirects int
	// Method indicates the HTTP method of the request, default GET.
	//
	//	request.Request("http://example.com", request.RequestOptions{
	//	  Method: http.MethodPost, // "POST"
	//	})
	Method string
	// Parameters are the URL parameters to be sent with the request.
	//
	//	resp, err := request.Request("http://example.com", request.RequestOptions{
	//	  Parameters: map[string][]string{
	//	    "name": {"John"},
	//	  },
	//	})
	//	// http://example.com?name=John
	Parameters map[string][]string
	// Timeout specifies the number of milliseconds before the request times out. This value will be
	// ignored if the `Content` field in the request options is set. It indicates no time-out
	// limitation if the value is -1.
	Timeout int
	// UserAgent sets the client's User-Agent field in the request header. It'll overwrite the value
	// of the `User-Agent` field in the request headers.
	UserAgent string
	// ValidateStatus defines whether the status code of the response is valid or not, and it'll
	// return an error if fails to validate the status code. Default, it sets the result to fail if
	// the status code is less than 200, or greater than and equal to 400.
	//
	//	resp, err := request.Request("http://example.com", request.RequestOptions{
	//	  ValidateStatus: func (status int) bool {
	//	    // Only success if the status code of response is 2XX
	//	    return status >= http.StatusOk && status <= http.StatusMultipleChoices
	//	  },
	//	})
	ValidateStatus func(int) bool
}

RequestOptions is the config for a request.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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