requests

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Jun 17, 2023 License: Apache-2.0 Imports: 30 Imported by: 13

README

Go Report Card Go.Dev reference Sourcegraph Release Goproxy.cn

基本介绍

GoRequests框架提供了强大便捷易用的HTTP客户端,基于http.Client进行扩展开发,对象创建可以通过requests.New()包方法,也可以通过new(requests.Client).Clone()方法调用,同时你还可以使用requests.NewHttpClient(requests.HttpClient(nil))创建对象。推荐使用new(requests.Client).Clone()来便捷地创建HTTP客户端对象。

安装

$ go get github.com/pkg6/go-requests

方法列表

https://pkg.golang.ir/github.com/pkg6/go-requests

基础使用

package main

import (
	"context"
	"fmt"
	"github.com/pkg6/go-requests"
	"net/url"
)

func main() {
	data := url.Values{}
	data.Set("k", "v")
	get, _ := requests.New().Get(context.Background(), "http://www.httpbin.org/get", data)
	defer get.Close()
	fmt.Println(get.ReadAllString())
	post, _ := requests.New().AsJson().Post(context.Background(), "http://www.httpbin.org/post", data)
	defer post.Close()
	fmt.Println(post.ReadAllString())
}

文件上传

u := url.Values{}
u.Set("服务端接受的name名称", "@file:loaclfile.txt")
request := requests.New()
request.PostForm(context.Background(), "http://127.0.0.1/upload", u)

返回对象

(r *Response) TraceInfo() TraceInfo
(r *Response) ReadAll() []byte
(r *Response) ReadAllString() string
(r *Response) GetCookieMap() map[string]string
(r *Response) GetCookie(key string) string
(r *Response) ContentType() string
(r *Response) Unmarshal(d any) error 
(r *Response) IsSuccess() bool
(r *Response) IsError() bool
(r *Response) Close() error 

加入我们

如果你认可我们的开源项目,有兴趣为 go-sms的发展做贡献,竭诚欢迎加入我们一起开发完善。无论是报告错误或是 Pull Request 开发,那怕是修改一个错别字也是对我们莫大的帮助。

License

go-requests is licensed under the Apache License 2.0 License - see the LICENSE file for details

Documentation

Index

Constants

View Source
const (
	HttpHeaderUserAgent       = `User-Agent`
	HttpHeaderContentType     = `Content-Type`
	HttpHeaderContentTypeJson = `application/json`
	HttpHeaderContentTypeXml  = `application/xml`
	HttpHeaderContentTypeForm = `application/x-www-form-urlencoded`
)

Variables

View Source
var (
	DefaultClient = New()
)
View Source
var (
	ErrAutoRedirectDisabled = errors.New("auto redirect is disabled")
)

Functions

func Base64Decode added in v0.0.2

func Base64Decode(str string) (string, error)

func Base64Encode added in v0.0.2

func Base64Encode(str string) string

func Base64File added in v0.0.2

func Base64File(path string) (string, error)

func Base64Reader added in v0.0.2

func Base64Reader(reader io.Reader) (string, error)

func HttpBuildQuery

func HttpBuildQuery(params map[string]any, parentKey string) string

HttpBuildQuery Generate get request parameters

func IsJSONType

func IsJSONType(s string) bool

IsJSONType method is to check JSON content type or not

func IsMatchString

func IsMatchString(expr string, s string) bool

func IsXMLType

func IsXMLType(s string) bool

IsXMLType method is to check XML content type or not

func MapCookiesToString added in v0.0.2

func MapCookiesToString(cookies map[string]string, cookieStr string) string

func Md5 added in v0.0.2

func Md5(str string) string

func Md5File added in v0.0.2

func Md5File(path string) (string, error)

func Md5Reader added in v0.0.2

func Md5Reader(reader io.Reader) (string, error)

func NewReadCloser

func NewReadCloser(content []byte, repeatable bool) io.ReadCloser

NewReadCloser creates and returns a RepeatReadCloser object.

func Sha1 added in v0.0.2

func Sha1(str string) string

func Sha256 added in v0.0.2

func Sha256(str string) string

func ToString

func ToString(any any) string

ToString converts `any` to string. It's most commonly used converting function.

func URLDecode added in v0.0.2

func URLDecode(str string) (string, error)

func URLEncode added in v0.0.2

func URLEncode(str string) string

func Uri

func Uri(uri string, query ...url.Values) *url.URL

Types

type Client

type Client struct {
	*http.Client
	// contains filtered or unexported fields
}

func New

func New() *Client

func NewHttpClient

func NewHttpClient(client *http.Client) *Client

func (*Client) AsForm

func (c *Client) AsForm() *Client

AsForm is a chaining function, which sets the HTTP content type as "application/x-www-form-urlencoded" for the next request.

func (*Client) AsJson

func (c *Client) AsJson() *Client

AsJson is a chaining function, which sets the HTTP content type as "application/json" for the next request.

Note that it also checks and encodes the parameter to JSON format automatically.

func (*Client) AsXml

func (c *Client) AsXml() *Client

AsXml is a chaining function, which sets the HTTP content type as "application/xml" for the next request.

Note that it also checks and encodes the parameter to XML format automatically.

func (*Client) BrowserMode

func (c *Client) BrowserMode() *Client

BrowserMode enables browser mode of the client. When browser mode is enabled, it automatically saves and sends cookie content from and to server.

func (*Client) Clone

func (c *Client) Clone() *Client

Clone Parameter initialization

func (*Client) Connect

func (c *Client) Connect(ctx context.Context, uri string, data any) (*Response, error)

Connect send CONNECT request and returns the response object. Note that the response object MUST be closed if it'll never be used.

func (*Client) Debug

func (c *Client) Debug() *Client

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, uri string, data any) (*Response, error)

Delete send DELETE request and returns the response object. Note that the response object MUST be closed if it'll never be used.

func (*Client) DoRequest

func (c *Client) DoRequest(ctx context.Context, method, uri string, body any) (response *Response, err error)

func (*Client) EnableTrace

func (c *Client) EnableTrace() *Client

func (*Client) Get

func (c *Client) Get(ctx context.Context, uri string, data any) (*Response, error)

Get send GET request and returns the response object. Note that the response object MUST be closed if it'll never be used.

func (*Client) Head

func (c *Client) Head(ctx context.Context, uri string, data any) (*Response, error)

Head send HEAD request and returns the response object. Note that the response object MUST be closed if it'll never be used.

func (*Client) Next

func (c *Client) Next(req *http.Request) (*Response, error)

Next calls the next middleware. This should only be call in HandlerFunc.

func (*Client) OnAfterRequest

func (c *Client) OnAfterRequest(callback requestCallback) *Client

OnAfterRequest method appends request callback into the before request chain.

client.OnAfterRequest(func(client *requests.Client, request *http.Request) error{
		// Now you have access to Client and Request instance
		// manipulate it as per your need

		return nil 	// if its success otherwise return error
	})

func (*Client) OnBeforeRequest

func (c *Client) OnBeforeRequest(callback clientCallback) *Client

OnBeforeRequest method appends request callback into the before request chain.

client.OnBeforeRequest(func(c *requests.Client) error {
		// Now you have access to Client and Request instance
		// manipulate it as per your need
		return nil 	// if its success otherwise return error
	})

func (*Client) OnError

func (c *Client) OnError(h ErrorHook) *Client

OnError method adds a callback that will be run whenever a request execution fails. This is called after all retries have been attempted (if any). If there was a response from the server, the error will be wrapped in *ResponseError which has the last response received from the server.

client.OnError(func(*http.Request, error){
	if v, ok := err.(*requests.ResponseError); ok {
		// Do something with v.Response
	}
	// Log the error, increment a metric, etc...
})

Out of the OnSuccess, OnError, OnInvalid, OnPanic callbacks, exactly one set will be invoked for each call to Request.Execute() that comletes.

func (*Client) OnPanic

func (c *Client) OnPanic(h ErrorHook) *Client

OnPanic method adds a callback that will be run whever a request execution panics.

Out of the OnSuccess, OnError, OnInvalid, OnPanic callbacks, exactly one set will be invoked for each call to Request.Execute() that completes. If an OnSuccess, OnError, or OnInvalid callback panics, then the exactly one rule can be violated.

func (*Client) OnResponse

func (c *Client) OnResponse(callback responseCallback) *Client

OnResponse method appends response callback into the after response chain.

client.OnResponse(func(request *http.Request, response *requests.Response) error {
		// Now you have access to Client and Response instance
		// manipulate it as per your need

		return nil 	// if its success otherwise return error
	})

func (*Client) OnSuccess

func (c *Client) OnSuccess(h SuccessHook) *Client

OnSuccess method adds a callback that will be run whenever a request execution succeeds. This is called after all retries have been attempted (if any).

Out of the OnSuccess, OnError, OnInvalid, OnPanic callbacks, exactly one set will be invoked for each call to Request.Execute() that comletes.

func (*Client) Options

func (c *Client) Options(ctx context.Context, uri string, data any) (*Response, error)

Options send OPTIONS request and returns the response object. Note that the response object MUST be closed if it'll never be used.

func (*Client) Patch

func (c *Client) Patch(ctx context.Context, uri string, data any) (*Response, error)

Patch send PATCH request and returns the response object. Note that the response object MUST be closed if it'll never be used.

func (*Client) Post

func (c *Client) Post(ctx context.Context, uri string, data any) (*Response, error)

Post sends request using HTTP method POST and returns the response object. Note that the response object MUST be closed if it'll never be used.

func (*Client) PostForm

func (c *Client) PostForm(ctx context.Context, uri string, data url.Values) (*Response, error)

PostForm is different from net/http.PostForm. It's a wrapper of Post method, which sets the Content-Type as "multipart/form-data;". and It will automatically set boundary characters for the request body and Content-Type.

It's Seem like the following case:

Content-Type: multipart/form-data; boundary=----Boundarye4Ghaog6giyQ9ncN

And form data is like: ------Boundarye4Ghaog6giyQ9ncN Content-Disposition: form-data; name="checkType"

none

It's used for sending form data. Note that the response object MUST be closed if it'll never be used.

func (*Client) PostJson

func (c *Client) PostJson(ctx context.Context, uri string, data any) (*Response, error)

func (*Client) Put

func (c *Client) Put(ctx context.Context, uri string, data any) (*Response, error)

Put send PUT request and returns the response object. Note that the response object MUST be closed if it'll never be used.

func (*Client) SetJSONMarshaler

func (c *Client) SetJSONMarshaler(marshaler func(v any) ([]byte, error)) *Client

SetJSONMarshaler method sets the JSON marshaler function to marshal the request body. By default, Resty uses `encoding/json` package to marshal the request body.

func (*Client) SetJSONUnmarshaler

func (c *Client) SetJSONUnmarshaler(unmarshaler func(data []byte, v any) error) *Client

SetJSONUnmarshaler method sets the JSON unmarshaler function to unmarshal the response body. By default, Resty uses `encoding/json` package to unmarshal the response body.

func (*Client) SetPrefix

func (c *Client) SetPrefix(prefix string) *Client

SetPrefix sets the request server URL prefix.

func (*Client) SetRetry

func (c *Client) SetRetry(retryCount int, retryWaitTime time.Duration) *Client

SetRetry is a chaining function, which sets retry count and interval when failure for next request.

func (*Client) SetTLSConfig

func (c *Client) SetTLSConfig(tlsConfig *tls.Config) *Client

SetTLSConfig sets the TLS configuration of client.

func (*Client) SetXMLMarshaler

func (c *Client) SetXMLMarshaler(marshaler func(v any) ([]byte, error)) *Client

SetXMLMarshaler method sets the XML marshaler function to marshal the request body. By default, Resty uses `encoding/xml` package to marshal the request body.

func (*Client) SetXMLUnmarshaler

func (c *Client) SetXMLUnmarshaler(unmarshaler func(data []byte, v any) error) *Client

SetXMLUnmarshaler method sets the XML unmarshaler function to unmarshal the response body. By default, Resty uses `encoding/xml` package to unmarshal the response body.

func (*Client) Timeout

func (c *Client) Timeout(t time.Duration) *Client

Timeout sets the request timeout for the client.

func (*Client) Trace

func (c *Client) Trace(ctx context.Context, uri string, data any) (*Response, error)

Trace send TRACE request and returns the response object. Note that the response object MUST be closed if it'll never be used.

func (*Client) Unmarshal

func (c *Client) Unmarshal(contentType string, b []byte, d any) (err error)

Unmarshal content into object from JSON or XML

func (*Client) Use

func (c *Client) Use(middlewares ...MiddlewareFunc) *Client

Use adds one or more middleware handlers to client.

func (*Client) WitchHttpClient added in v0.0.2

func (c *Client) WitchHttpClient(client *http.Client) *Client

func (*Client) WithBasicAuth

func (c *Client) WithBasicAuth(username, password string) *Client

WithBasicAuth Specify the basic authentication username and password for the request.

func (*Client) WithContentType

func (c *Client) WithContentType(contentType string) *Client

WithContentType is a chaining function, which sets HTTP content type for the next request.

func (*Client) WithCookie

func (c *Client) WithCookie(k, v string) *Client

func (*Client) WithCookieJar

func (c *Client) WithCookieJar(jar http.CookieJar) *Client

func (*Client) WithCookieString

func (c *Client) WithCookieString(cookie string) *Client

func (*Client) WithCookies

func (c *Client) WithCookies(cookies map[string]string) *Client

func (*Client) WithHeader

func (c *Client) WithHeader(header, value string) *Client

WithHeader method sets a single header field and its value in the client instance. These headers will be applied to all requests raised from this client instance. Also it can be overridden at request level header options.

WithHeader("Content-Type", "application/json").
WithHeader("Accept", "application/json")

func (*Client) WithHeaderVerbatim

func (c *Client) WithHeaderVerbatim(header, value string) *Client

WithHeaderVerbatim method is to set a single header field and its value verbatim in the current request.

For Example: To set `all_lowercase` and `UPPERCASE` as `available`.

WithHeaderVerbatim("all_lowercase", "available").
WithHeaderVerbatim("UPPERCASE", "available")

Also you can override header value, which was set at client instance level.

func (*Client) WithHeaders

func (c *Client) WithHeaders(headers map[string]string) *Client

WithHeaders method sets multiple headers field and its values at one go in the client instance. These headers will be applied to all requests raised from this client instance. Also it can be overridden at request level headers options. For Example: To set `Content-Type` and `Accept` as `application/json`

WithHeaders(map[string]string{
	"Content-Type": "application/json",
	"Accept": "application/json",
})

func (*Client) WithProxyUrl

func (c *Client) WithProxyUrl(proxyURL string) *Client

WithProxyUrl set proxy for the client. This func will do nothing when the parameter `proxyURL` is empty or in wrong pattern. The correct pattern is like `http://USER:PASSWORD@IP:PORT` or `socks5://USER:PASSWORD@IP:PORT`. Only `http` and `socks5` proxies are supported currently.

func (*Client) WithRedirectLimit

func (c *Client) WithRedirectLimit(redirectLimit int) *Client

WithRedirectLimit limits the number of jumps.

func (*Client) WithRedirectPolicy

func (c *Client) WithRedirectPolicy(policies ...any) *Client

WithRedirectPolicy method sets the client redirect poilicy. Resty provides ready to use redirect policies. Wanna create one for yourself refer to `redirect.go`.

WithRedirectLimit(20)
WithRedirectPolicy(FlexibleRedirectPolicy(20))
WithRedirectPolicy(FlexibleRedirectPolicy(20), DomainCheckRedirectPolicy("host1.com", "host2.net"))

func (*Client) WithTLSKeyCrt

func (c *Client) WithTLSKeyCrt(crtFile, keyFile string) *Client

WithTLSKeyCrt sets the certificate and key file for TLS configuration of client.

func (*Client) WithToken

func (c *Client) WithToken(token string, Type ...string) *Client

WithToken Specify an authorization token for the request.

func (*Client) WithUserAgent

func (c *Client) WithUserAgent(userAgent string) *Client

type ErrorHook

type ErrorHook func(client *Client, request *http.Request, err error)

type MiddlewareFunc

type MiddlewareFunc = func(c *Client, r *http.Request) (*Response, error)

MiddlewareFunc middleware handler func

type ReadCloser

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

ReadCloser implements the io.ReadCloser interface which is used for reading request body content multiple times.

Note that it cannot be closed.

func (*ReadCloser) Close

func (b *ReadCloser) Close() error

Close implements the io.ReadCloser interface.

func (*ReadCloser) Read

func (b *ReadCloser) Read(p []byte) (n int, err error)

Read implements the io.ReadCloser interface.

type RedirectPolicy

type RedirectPolicy interface {
	Apply(req *http.Request, via []*http.Request) error
}

RedirectPolicy to regulate the redirects in the resty client. Objects implementing the RedirectPolicy interface can be registered as

Apply function should return nil to continue the redirect jounery, otherwise return error to stop the redirect.

func DomainCheckRedirectPolicy

func DomainCheckRedirectPolicy(hostnames ...string) RedirectPolicy

DomainCheckRedirectPolicy is convenient method to define domain name redirect rule in resty client. Redirect is allowed for only mentioned host in the policy.

requests.WithRedirectPolicy(DomainCheckRedirectPolicy("host1.com", "host2.org", "host3.net"))

func FlexibleRedirectPolicy

func FlexibleRedirectPolicy(noOfRedirect int) RedirectPolicy

FlexibleRedirectPolicy is convenient method to create No of redirect policy for HTTP client.

requests.SetRedirectPolicy(FlexibleRedirectPolicy(20))

func NoRedirectPolicy

func NoRedirectPolicy() RedirectPolicy

NoRedirectPolicy is used to disable redirects in the HTTP client

requests.WithRedirectPolicy(NoRedirectPolicy())

type RedirectPolicyFunc

type RedirectPolicyFunc func(*http.Request, []*http.Request) error

The RedirectPolicyFunc type is an adapter to allow the use of ordinary functions as RedirectPolicy. If f is a function with the appropriate signature, RedirectPolicyFunc(f) is a RedirectPolicy object that calls f.

func (RedirectPolicyFunc) Apply

func (f RedirectPolicyFunc) Apply(req *http.Request, via []*http.Request) error

Apply calls f(req, via).

type Response

type Response struct {
	*http.Response // Response is the underlying http.Response object of certain request.
	// contains filtered or unexported fields
}

func Connect

func Connect(uri string, data any, args ...func(client *Client)) (*Response, error)

func Delete

func Delete(uri string, data any, args ...func(client *Client)) (*Response, error)

func Get

func Get(uri string, data any, args ...func(client *Client)) (*Response, error)
func Head(uri string, data any, args ...func(client *Client)) (*Response, error)

func Options

func Options(uri string, data any, args ...func(client *Client)) (*Response, error)

func Patch

func Patch(uri string, data any, args ...func(client *Client)) (*Response, error)

func Post

func Post(uri string, data any, args ...func(client *Client)) (*Response, error)

func PostForm

func PostForm(uri string, data url.Values, args ...func(client *Client)) (*Response, error)

func PostJson

func PostJson(uri string, data any, args ...func(client *Client)) (*Response, error)

func Put

func Put(uri string, data any, args ...func(client *Client)) (*Response, error)

func Request

func Request(method, uri string, data any, args ...func(client *Client)) (*Response, error)

func Trace

func Trace(uri string, data any, args ...func(client *Client)) (*Response, error)

func (*Response) Close

func (r *Response) Close() error

Close closes the response when it will never be used.

func (*Response) ContentType

func (r *Response) ContentType() string

ContentType response header Content-Type

func (*Response) GetCookie

func (r *Response) GetCookie(key string) string

func (*Response) GetCookieMap

func (r *Response) GetCookieMap() map[string]string

func (*Response) GetCookieString added in v0.0.2

func (r *Response) GetCookieString() string

func (*Response) IsError

func (r *Response) IsError() bool

IsError method returns true if HTTP status `code >= 400` otherwise false.

func (*Response) IsSuccess

func (r *Response) IsSuccess() bool

IsSuccess method returns true if HTTP status `code >= 200 and <= 299` otherwise false.

func (*Response) ReadAll

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

ReadAll retrieves and returns the response content as []byte.

func (*Response) ReadAllString

func (r *Response) ReadAllString() string

ReadAllString retrieves and returns the response content as string.

func (*Response) TraceInfo

func (r *Response) TraceInfo() TraceInfo

func (*Response) Unmarshal

func (r *Response) Unmarshal(d any) error

Unmarshal content into object from JSON or XML

type ResponseError

type ResponseError struct {
	Response *Response
	Err      error
}

func (*ResponseError) Error

func (e *ResponseError) Error() string

type SuccessHook

type SuccessHook func(client *Client, response *Response)

type TraceInfo

type TraceInfo struct {
	// DNSLookup is a duration that transport took to perform
	// DNS lookup.
	DNSLookup time.Duration
	// ConnTime is a duration that took to obtain a successful connection.
	ConnTime time.Duration
	// TCPConnTime is a duration that took to obtain the TCP connection.
	TCPConnTime time.Duration
	// TLSHandshake is a duration that TLS handshake took place.
	TLSHandshake time.Duration
	// ServerTime is a duration that server took to respond first byte.
	ServerTime time.Duration
	// ResponseTime is a duration since first response byte from server to
	// request completion.
	ResponseTime time.Duration
	// TotalTime is a duration that total request took end-to-end.
	TotalTime time.Duration
	// IsConnReused is whether this connection has been previously
	// used for another HTTP request.
	IsConnReused bool
	// IsConnWasIdle is whether this connection was obtained from an
	// idle pool.
	IsConnWasIdle bool
	// ConnIdleTime is a duration how long the connection was previously
	// idle, if IsConnWasIdle is true.
	ConnIdleTime time.Duration
	// RequestAttempt is to represent the request attempt made during a Resty
	// request execution flow, including retry count.
	RequestAttempt int
	// RemoteAddr returns the remote network address.
	RemoteAddr net.Addr
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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