requester

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2021 License: Apache-2.0 Imports: 20 Imported by: 0

README

About

This package is a library of allan577 project. This library provides an efficient and easy-to-use HTTP client.

Install

go get -u -v gitee.com/allan577/go-lib-requester

Usage

package main

import (
    "fmt"

    "gitee.com/allan577/go-lib-requester"
)

func main() {
    client := requester.Default()

    // client.Get("https://test.com", nil)
    res, err := client.New("https://test.com").Get()
    if err != nil {
        panic(err)
    }
    fmt.Println(res.String())

    data := map[string]interface{}{"key": "value"}
    // client.PostJSON("https://test.com", data)
    res, err = client.New("https://test.com").WithJSONBody(data).Post()
    if err != nil {
        panic(err)
    }

    obj := make(map[string]interface{})
    // Bind response json to object.
    if err = res.JSON(&obj); err != nil {
        panic(err)
    }

    // client.UploadFile("https://test.com", "upload", "path/to/file")
    res, err = client.New("https://test.com").WithFormDataFile("upload", "path/to/file").Upload()
    if err != nil {
        panic(err)
    }
    fmt.Println(res.String())
}

License

Apache-2.0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrEmptyRequestURL represents an empty request url error.
	// When sending a request, this error will be returned if the given request url is empty.
	ErrEmptyRequestURL = errors.New("empty request url")

	// ErrInvalidRequestBody indicates an invalid request body error.
	// When sending a request, if the bound request body cannot be recognized, this error is returned.
	ErrInvalidRequestBody = errors.New("invalid request body")

	// ErrEmptyUploadBody represents an empty upload body error.
	// When sending an upload request, this error is returned when the upload data is empty.
	ErrEmptyUploadBody = errors.New("empty upload body")

	// ErrInvalidUploadBody indicates an invalid upload body error.
	// When sending an upload request, this error is returned when the bound upload data is invalid.
	ErrInvalidUploadBody = errors.New("invalid upload body")
)

Functions

func DefaultHTTPClient

func DefaultHTTPClient() *http.Client

DefaultHTTPClient returns the built-in default HTTP client instance.

func NewDefaultHTTPClient

func NewDefaultHTTPClient() *http.Client

NewDefaultHTTPClient returns a new default HTTP client instance.

Types

type Client

type Client interface {
	// SetHTTPClient sets a private HTTP client instance for the current client.
	// If a nil is given, the built-in default HTTP client is used.
	SetHTTPClient(*http.Client) Client

	// SetTimeout sets a request timeout period for the current client.
	// Setting it to 0 will never time out.
	// This timeout period can be overridden by each request timeout setting.
	SetTimeout(time.Duration) Client

	// GetCommonHeaders returns the common request headers of the current client.
	GetCommonHeaders() http.Header

	// SetCommonHeader sets a common request header of the current client.
	// If the given request header value is an empty string, the corresponding request
	// header will be deleted.
	SetCommonHeader(string, string) Client

	// SetCommonHeaders resets the common request headers of the current client.
	// If nil is given, all common request headers will be deleted.
	SetCommonHeaders(http.Header) Client

	// SetResponder sets the given responder to the current client.
	SetResponder(Responder) Client

	// New returns a new request instance from the given uri.
	New(string) Request

	// Do obtains and initializes the request object from the global request object pool,
	// and will immediately reclaim the request object after the given closure is completed.
	// This method assumes that the request object will not be referenced by space outside the closure.
	Do(string, func(Request) (Response, error)) (Response, error)

	// Head uses the given parameters to send a request and return the Response.
	// This method will send the request using the HEAD method.
	Head(string, url.Values) (Response, error)

	// Get uses the given parameters to send a request and return the Response.
	// This method will send the request using the GET method.
	Get(string, url.Values) (Response, error)

	// Post uses the given parameters to send a request and return the Response.
	// This method will send the request using the POST method.
	Post(string, interface{}) (Response, error)

	// PostJSON uses the given parameters to send a request and return the Response.
	// This method will send the request using the POST method.
	// This method encodes the request body as json data and sends it.
	PostJSON(string, interface{}) (Response, error)

	// PostXML uses the given parameters to send a request and return the Response.
	// This method will send the request using the POST method.
	// This method encodes the request body as xml data and sends it.
	PostXML(string, interface{}) (Response, error)

	// PostForm uses the given parameters to send a request and return the Response.
	// This method will send the request using the POST method.
	// This method encodes the request body as form data (urlencoded) and sends it.
	PostForm(string, url.Values) (Response, error)

	// UploadFile uploads a file with the given parameters and returns the Response.
	// This method will send the request using the POST method.
	// This method encodes the request body as form data and sends it.
	// This method supports using string paths, opened file descriptors and downstream
	// uploaded files as upload targets.
	UploadFile(string, string, interface{}) (Response, error)
}

The Client interface defines the requester client.

func Default

func Default() Client

Default function returns the built-in default client instance.

func New

func New() Client

The New function creates and returns a new built-in Client instance.

type Request

type Request interface {
	// WithMethod adds the default request method of the current request.
	WithMethod(string) Request

	// WithResponder adds the given responder to the current request.
	WithResponder(Responder) Request

	// WithHeader adds a request header to the current request.
	// If the given request header value is an empty string, the corresponding request
	// header will be deleted.
	WithHeader(string, string) Request

	// WithContentType adds the ContentType header information of the current request.
	WithContentType(string) Request

	// WithHeaders adds and replaces some headers to the current request.
	WithHeaders(http.Header) Request

	// WithContext adds a context to the current request.
	// If the given context is nil, context.Background() is automatically used.
	WithContext(context.Context) Request

	// WithQuery adds a query parameter to the current request.
	WithQuery(string, string) Request

	// WithQueryValue adds a query parameter to the current request.
	// This method will automatically convert the given parameter value to a string.
	WithQueryValue(string, interface{}) Request

	// WithQueries adds and replaces some query parameters to the current request.
	WithQueries(url.Values) Request

	// WithTimeout adds a timeout for the current request.
	// If the given timeout period is zero, the client's timeout setting is used.
	WithTimeout(time.Duration) Request

	// WithBody adds request body to the current request.
	WithBody(interface{}) Request

	// WithJSONBody adds the request body as json.
	// This method will force set "Content-Type" to "application/json".
	WithJSONBody(interface{}) Request

	// WithRawJSONBody adds the request body as raw json.
	// This method will force set "Content-Type" to "application/json".
	WithRawJSONBody([]byte) Request

	// WithXMLBody adds the request body as xml.
	// This method will force set "Content-Type" to "application/xml".
	WithXMLBody(interface{}) Request

	// WithRawXMLBody adds the request body as raw xml.
	// This method will force set "Content-Type" to "application/xml".
	WithRawXMLBody([]byte) Request

	// WithFormBody adds the request body as form (urlencoded).
	// This method will force set "Content-Type" to "application/x-www-form-urlencoded".
	WithFormBody(url.Values) Request

	// Head sends the current request and returns the received response.
	// This method will send the request using the HEAD method.
	Head() (Response, error)

	// Get sends the current request and returns the received response.
	// This method will send the request using the GET method.
	Get() (Response, error)

	// Post sends the current request and returns the received response.
	// This method will send the request using the POST method.
	Post() (Response, error)

	// Send sends the current request and returns the received response.
	Send() (Response, error)

	// SendBy sends the current request and returns the received response.
	// This method will send the request using the given request method.
	SendBy(string) (Response, error)

	// WithFormDataField adds a form data for uploading to the current request.
	// If the given form value is nil, delete the corresponding form key.
	WithFormDataField(string, interface{}) Request

	// WithFormDataFile adds a file target for uploading to the current request.
	// If the given form value is nil, delete the corresponding form key.
	// This method supports adding string paths, opened file descriptors and
	// downstream uploaded files as upload targets.
	WithFormDataFile(string, interface{}) Request

	// WithFormDataFileFromReader adds an upload target to the current request from
	// the given reader and file name.
	// If the given reader is nil, delete the corresponding form key.
	WithFormDataFileFromReader(string, string, io.Reader) Request

	// ClearFormData removes all uploaded form data from the current request.
	// If you need to reuse the current request instance to send multiple upload requests,
	// you should clean up each time before setting new form data (for the added file descriptor,
	// because the position of the cursor is uncertain, it may cause unexpected results ).
	ClearFormData() Request

	// Upload sends the current upload request and receives the response.
	// This method will send the request using the POST method.
	Upload() (Response, error)

	// UploadBy sends the current upload request and receives the response.
	// This method will send the request using the given request method.
	// This method only supports POST method and PUT method.
	UploadBy(string) (Response, error)

	// Clear cleans up the current request instance so that it can be reused.
	// This method will not cut the connection with the client, nor will it
	// change the request url.
	Clear() Request
}

Request interface defines client requests.

type Responder

type Responder func(r *http.Response, noBody bool) (Response, error)

Responder defines the Response instance factory. In some scenarios, users want to freely control the processing method of http response data stream, especially for large response volume (download file). At this time, the responder can be specified in the global or single request to take over the control of the data stream. If noBody is true, the response body is discarded (HEAD request), however, the specific processing scheme is decided by users themselves.

type Response

type Response interface {
	fmt.Stringer

	// Headers method returns all response headers.
	Headers() http.Header

	// StatusCode returns the status code of the response.
	StatusCode() int

	// Status returns the status text of the response.
	Status() string

	// Body returns the response body, or nil if there is no response body.
	// For HEAD request, nil is always returned.
	Body() []byte

	// Len returns the length of the response body.
	Len() int

	// JSON binds the response body to the given object as json.
	JSON(interface{}) error

	// XML binds the response body to the given object as xml.
	XML(interface{}) error
}

Response interface defines the HTTP response result.

func NewEmptyResponse

func NewEmptyResponse() Response

NewEmptyResponse creates and returns a new empty response instance. The returned response instance only implements the Response interface and has no meaningful data and behavior. This empty response can be used as an embedded object to help users implement their own response instances instead of implementing all the Response interface methods.

func NewResponse

func NewResponse(o *http.Response, noBody bool) (Response, error)

NewResponse returns a built-in implementation of the Response interface from a given http.Response instance. If noBody is true, the response body is discarded.

func NewResponseFrom

func NewResponseFrom(body []byte, headers http.Header, code int, status ...string) Response

NewResponseFrom creates and returns a Response instance from the given response data. This function is used to create a custom Response. Panic if too many status parameters. If the status parameter is not given, we will automatically use http.StatusText to convert the code to the status string.

Jump to

Keyboard shortcuts

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