request

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 16, 2023 License: MIT Imports: 11 Imported by: 0

README

HTTP Request tool for Go

test codecov Version Badge License Badge Go Reference

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

Features

  • Timeouts or self-control context.
  • Serialize request body automatically.
  • Response body deserialization wrapper.

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://dummyjson.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://dummyjson.com/products/add", 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://dummyjson.com/products/add", 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://dummyjson.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://dummyjson.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://dummyjson.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.
Timeout int Timeout in milliseconds.

Request Config

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

Field Type Description
BaseURL string The base url for all requests that performing by this client instance.
Parameters map[string][]string Custom query string parameters to be sent.
Headers map[string][]string Custom headers to be sent.
Timeout int Timeout in milliseconds.
Context context.Context Self-control context.
Body any The request body.
Method string HTTP request method, default GET.
ContentType string The content type of this request, default application/json if it's empty.

Roadmap

  • Request and response intercepts.
  • URL encoded form serialization/deserialization.

Documentation

Index

Constants

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

Variables

View Source
var ErrNoURL error = errors.New("no url")

ErrNoURL throws when no uri and base url set in the request.

View Source
var ErrUnsupportedContentType = errors.New("unsupported content type")

Functions

func DELETE

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

func GET

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

func OPTIONS

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

func PATCH

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

func POST

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

func PUT

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

func Request

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

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.

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.

Types

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
	// contains filtered or unexported fields
}

func New

func New(config ...Config) *Client

New creates and returns a new Client instance.

func (*Client) DELETE

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

func (*Client) GET

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

func (*Client) HEAD

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

func (*Client) OPTIONS

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

func (*Client) PATCH

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

func (*Client) POST

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

func (*Client) PUT

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

func (*Client) Request

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

type Config

type Config struct {
	// BaseURL will be prepended to all request URL unless URL is absolute.
	BaseURL string
	// Timeout is request timeout in milliseconds.
	Timeout int
	// 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
}

type RequestOptions

type RequestOptions struct {
	BaseURL     string
	Timeout     int
	Context     context.Context
	Parameters  map[string][]string
	Headers     map[string][]string
	Body        any
	Method      string
	ContentType string
}

Jump to

Keyboard shortcuts

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