requests

package module
v0.0.19 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2023 License: Apache-2.0 Imports: 34 Imported by: 13

README

Test Status Go Report Card Go.Dev reference Sourcegraph Release

基本介绍

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

安装

$ go get 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.PostFormWithFiles(context.Background(), "http://127.0.0.1/upload", u)

stream请求与返回处理

ChatGPT【以微软为例】

package main

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

func main() {
	payload := `{
  "messages": [
    {
      "role": "system",
      "content": "You are an AI assistant that helps people find information."
    },
    {
      "role": "user",
      "content": "你是谁"
    }
  ],
  "model":"gpt-35-turbo",
  "temperature": 0.7,
  "top_p": 0.95,
  "frequency_penalty": 0,
  "presence_penalty": 0,
  "max_tokens": 800,
  "stop": null,
  "stream":true 
}`

	json, _ := requests.PostJson("end-point url", payload, func(client *requests.Client) {
		client.WithHeader("api-key", "api-key")
	})
	defer json.Close()
	json.ReadStream(func(line []byte, number int64) {
		fmt.Println(string(line))
	})
}

方法列表

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

返回对象

(r *Response) Close() error
(r *Response) TraceInfo() TraceInfo
(r *Response) GetCookie() Cookie
(r *Response) ReadAll() []byte
(r *Response) ReadStream(lineNumberFun func(line []byte, number int64)) int64
(r *Response) ReadAllString() string
(r *Response) ContentType() string
(r *Response) Unmarshal(d any) error
(r *Response) IsSuccess() bool
(r *Response) IsError() bool

加入我们

如果你认可我们的开源项目,有兴趣为 go-requests 的发展做贡献,竭诚欢迎加入我们一起开发完善。无论是报告错误或是 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 (
	HttpHeaderHost   = `Host`
	HttpHeaderCookie = `Cookie`

	HttpHeaderUserAgent     = `User-Agent`
	HttpHeaderAuthorization = "Authorization"
	HttpHeaderAccept        = "Accept"
	HttpMIMEEventStream     = "text/event-stream"
	HttpHeaderCacheControl  = "Cache-Control"
	HttpHeaderConnection    = "Connection"
	HttpHeaderContentType   = `Content-Type`

	HttpHeaderContentTypeJson            = `application/json`
	HttpHeaderContentTypeJsonCharsetUTF8 = HttpHeaderContentTypeJson + "; " + charsetUTF8
	HttpHeaderContentTypeXml             = `application/xml`
	HttpHeaderContentTypeXmlCharsetUTF8  = HttpHeaderContentTypeXml + "; " + charsetUTF8
	HttpHeaderContentTypeForm            = `application/x-www-form-urlencoded`

	AuthorizationTypeBearer = "Bearer "
	AuthorizationTypeBasic  = "Basic "
)

Variables

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

Functions

func AnyString added in v0.0.15

func AnyString(any any) string

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

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 Base64StdEncoding added in v0.0.4

func Base64StdEncoding(base64Str string) io.Reader

func ConnectUnmarshal added in v0.0.6

func ConnectUnmarshal(uri string, data, d any, args ...ArgsFunc) error

func DefaultHttpClient added in v0.0.7

func DefaultHttpClient(localAddr net.Addr) *http.Client

DefaultHttpClient set InsecureSkipVerify = false c.Client.Transport.(*http.Transport).TLSClientConfig.InsecureSkipVerify = false

func DeleteUnmarshal added in v0.0.6

func DeleteUnmarshal(uri string, data, d any, args ...ArgsFunc) error

func GetUnmarshal added in v0.0.6

func GetUnmarshal(uri string, data, d any, args ...ArgsFunc) error

func HeadUnmarshal added in v0.0.6

func HeadUnmarshal(uri string, data, d any, args ...ArgsFunc) error

func HttpBuildQuery

func HttpBuildQuery(data map[string]any) 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 IsStreamType added in v0.0.9

func IsStreamType(s string) bool

func IsXMLType

func IsXMLType(s string) bool

IsXMLType method is to check XML content type or not

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)

Md5Reader f, _ := os.Open("./_example/1.jpeg") f.Seek(0, 0) requests.Md5Reader(f)

func NewReadCloser

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

NewReadCloser creates and returns a RepeatReadCloser object.

func OptionsUnmarshal added in v0.0.6

func OptionsUnmarshal(uri string, data, d any, args ...ArgsFunc) error

func PatchUnmarshal added in v0.0.6

func PatchUnmarshal(uri string, data, d any, args ...ArgsFunc) error

func PostFormUnmarshal added in v0.0.6

func PostFormUnmarshal(uri string, data url.Values, d any, args ...ArgsFunc) error

func PostFormWithFilesUnmarshal added in v0.0.6

func PostFormWithFilesUnmarshal(uri string, data url.Values, d any, args ...ArgsFunc) error

func PostJsonUnmarshal added in v0.0.6

func PostJsonUnmarshal(uri string, data, d any, args ...ArgsFunc) error

func PostUnmarshal added in v0.0.6

func PostUnmarshal(uri string, data, d any, args ...ArgsFunc) error

func PutUnmarshal added in v0.0.6

func PutUnmarshal(uri string, data, d any, args ...ArgsFunc) error

func RandomMobileUserAgent added in v0.0.14

func RandomMobileUserAgent() string

RandomMobileUserAgent generates a random MOBILE browser user-agent on every requests

func RandomUserAgent added in v0.0.14

func RandomUserAgent() string

RandomUserAgent generates a random DESKTOP browser user-agent on every requests

func RequestRoute added in v0.0.6

func RequestRoute(route IRoute) error

RequestRoute

route := &requests.Route{
		Uri:    "https://api.github.com/users/github",
		Method: http.MethodGet,
		D:      &.tests.GitHubUser{},
	}
	_ = requests.RequestRoute(route)
	fmt.Println(route.GetD().(*.tests.GitHubUser))

func RequestUnmarshal added in v0.0.6

func RequestUnmarshal(method, uri string, data, d any, args ...ArgsFunc) error

func RequestUnmarshalSaveFile added in v0.0.7

func RequestUnmarshalSaveFile(method, uri string, data, d any, fileName string, args ...ArgsFunc) error

RequestUnmarshalSaveFile

var resp _testdata.GitHubUser
err := requests.RequestUnmarshalSaveFile(http.MethodGet,
	"https://api.github.com/users/github",
	nil, &resp, "github_user.log")
fmt.Println(err)
fmt.Println(resp)

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 TraceUnmarshal added in v0.0.6

func TraceUnmarshal(uri string, data, d any, args ...ArgsFunc) error

func URIQuery added in v0.0.13

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

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 UrlValues added in v0.0.6

func UrlValues(uvs ...url.Values) url.Values

Types

type ArgsFunc added in v0.0.3

type ArgsFunc func(client *Client)

func Debug added in v0.0.3

func Debug() ArgsFunc

func SetTLSConfig added in v0.0.3

func SetTLSConfig(tlsConfig *tls.Config) ArgsFunc

func WithBasicAuth added in v0.0.3

func WithBasicAuth(username, password string) ArgsFunc

func WithContentType added in v0.0.3

func WithContentType(contentType string) ArgsFunc

func WithCookie added in v0.0.3

func WithCookie(k, v string) ArgsFunc

func WithCookies added in v0.0.3

func WithCookies(cookies map[string]string) ArgsFunc

func WithHeader added in v0.0.3

func WithHeader(header, value string) ArgsFunc

func WithHeaders added in v0.0.3

func WithHeaders(headers map[string]string) ArgsFunc

func WithProxyUrl added in v0.0.3

func WithProxyUrl(proxyURL string) ArgsFunc

func WithTLSKeyCrt added in v0.0.3

func WithTLSKeyCrt(crtFile, keyFile string) ArgsFunc

func WithToken added in v0.0.3

func WithToken(token string, Type ...string) ArgsFunc

func WithUserAgent added in v0.0.3

func WithUserAgent(userAgent string) ArgsFunc

type CacheInterface added in v0.0.18

type CacheInterface interface {
	Set(key, value string, ttl time.Duration) error
	Get(key string) (string, error)
	Has(key string) bool
	Delete(key string) error
	CleanExpired()
}

func NewFileCache added in v0.0.8

func NewFileCache(paths ...string) CacheInterface

NewFileCache

go func() {
	ticker := time.NewTicker(time.Minute * 5)
	for range ticker.C {
		cache.CleanExpired()
	}
}()

type Client

type Client struct {
	*http.Client
	Debug bool

	BaseUrl       string
	Query         url.Values
	Header        http.Header
	Cookie        Cookie
	Logger        LoggerInterface
	JSONMarshal   func(v any) ([]byte, error)
	JSONUnmarshal func(data []byte, v any) error
	XMLMarshal    func(v any) ([]byte, error)
	XMLUnmarshal  func(data []byte, v any) error
	// contains filtered or unexported fields
}

func NewClient added in v0.0.17

func NewClient() *Client

func (*Client) AsForm

func (c *Client) AsForm() ClientInterface

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() ClientInterface

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() ClientInterface

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() ClientInterface

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() ClientInterface

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) ConnectBytes added in v0.0.7

func (c *Client) ConnectBytes(ctx context.Context, uri string, data any) ([]byte, error)

func (*Client) ConnectUnmarshal added in v0.0.16

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

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) DeleteBytes added in v0.0.7

func (c *Client) DeleteBytes(ctx context.Context, uri string, data any) ([]byte, error)

func (*Client) DeleteUnmarshal added in v0.0.16

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

func (*Client) DoRequest

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

func (*Client) DoRequestBytes added in v0.0.7

func (c *Client) DoRequestBytes(ctx context.Context, method string, uri string, data any) ([]byte, error)

func (*Client) DoRequestUnmarshal added in v0.0.16

func (c *Client) DoRequestUnmarshal(ctx context.Context, method string, uri string, data, d any) error

func (*Client) EnableDebug added in v0.0.18

func (c *Client) EnableDebug() ClientInterface

func (*Client) EnableTrace

func (c *Client) EnableTrace() ClientInterface

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) GetBytes added in v0.0.7

func (c *Client) GetBytes(ctx context.Context, uri string, data any) ([]byte, error)

func (*Client) GetUnmarshal added in v0.0.16

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

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) HeadBytes added in v0.0.7

func (c *Client) HeadBytes(ctx context.Context, uri string, data any) ([]byte, error)

func (*Client) HeadUnmarshal added in v0.0.16

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

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) ClientInterface

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) ClientInterface

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) ClientInterface

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) ClientInterface

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) ClientInterface

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) ClientInterface

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) OptionsBytes added in v0.0.7

func (c *Client) OptionsBytes(ctx context.Context, uri string, data any) ([]byte, error)

func (*Client) OptionsUnmarshal added in v0.0.16

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

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) PatchBytes added in v0.0.7

func (c *Client) PatchBytes(ctx context.Context, uri string, data any) ([]byte, error)

func (*Client) PatchUnmarshal added in v0.0.16

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

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) PostBytes added in v0.0.7

func (c *Client) PostBytes(ctx context.Context, uri string, data any) ([]byte, error)

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) PostFormBytes added in v0.0.7

func (c *Client) PostFormBytes(ctx context.Context, uri string, data url.Values) ([]byte, error)

func (*Client) PostFormUnmarshal added in v0.0.16

func (c *Client) PostFormUnmarshal(ctx context.Context, uri string, data url.Values, d any) error

func (*Client) PostFormWithFiles added in v0.0.4

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

PostFormWithFiles 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) PostFormWithFilesBytes added in v0.0.7

func (c *Client) PostFormWithFilesBytes(ctx context.Context, uri string, data url.Values) ([]byte, error)

func (*Client) PostFormWithFilesUnmarshal added in v0.0.16

func (c *Client) PostFormWithFilesUnmarshal(ctx context.Context, uri string, data url.Values, d any) error

func (*Client) PostJson

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

func (*Client) PostJsonBytes added in v0.0.7

func (c *Client) PostJsonBytes(ctx context.Context, uri string, data any) ([]byte, error)

func (*Client) PostJsonUnmarshal added in v0.0.16

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

func (*Client) PostUnmarshal added in v0.0.16

func (c *Client) PostUnmarshal(ctx context.Context, uri string, data, d any) 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) PutBytes added in v0.0.7

func (c *Client) PutBytes(ctx context.Context, uri string, data any) ([]byte, error)

func (*Client) PutUnmarshal added in v0.0.16

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

func (*Client) SetBaseURL added in v0.0.7

func (c *Client) SetBaseURL(baseUrl string) ClientInterface

func (*Client) SetCheckRedirect added in v0.0.17

func (c *Client) SetCheckRedirect(fn func(req *http.Request, via []*http.Request) error)

func (*Client) SetCookie added in v0.0.17

func (c *Client) SetCookie(cookie Cookie) ClientInterface

func (*Client) SetDebug added in v0.0.7

func (c *Client) SetDebug(debug bool) ClientInterface

func (*Client) SetHeader added in v0.0.17

func (c *Client) SetHeader(header http.Header) ClientInterface

func (*Client) SetHttpClient added in v0.0.17

func (c *Client) SetHttpClient(client *http.Client) ClientInterface

func (*Client) SetJSONMarshaler

func (c *Client) SetJSONMarshaler(marshaler func(v interface{}) ([]byte, error)) ClientInterface

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

func (*Client) SetJSONUnmarshaler

func (c *Client) SetJSONUnmarshaler(unmarshaler func(data []byte, v interface{}) error) ClientInterface

SetJSONUnmarshaler method sets the JSON unmarshaler function to unmarshal the response body.

func (*Client) SetLogger added in v0.0.18

func (c *Client) SetLogger(logger LoggerInterface) ClientInterface

func (*Client) SetQuery added in v0.0.7

func (c *Client) SetQuery(query url.Values) ClientInterface

func (*Client) SetRetry

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

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) ClientInterface

SetTLSConfig sets the TLS configuration of client.

func (*Client) SetTimeout added in v0.0.17

func (c *Client) SetTimeout(t time.Duration) ClientInterface

SetTimeout sets the request timeout for the client.

func (*Client) SetWriter added in v0.0.14

func (c *Client) SetWriter(writer io.Writer) ClientInterface

func (*Client) SetXMLMarshaler

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

SetXMLMarshaler method sets the XML marshaler function to marshal the request body.

func (*Client) SetXMLUnmarshaler

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

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

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) TraceBytes added in v0.0.7

func (c *Client) TraceBytes(ctx context.Context, uri string, data any) ([]byte, error)

func (*Client) TraceUnmarshal added in v0.0.16

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

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) ClientInterface

Use adds one or more middleware handlers to client.

func (*Client) WithBasicAuth

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

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

func (*Client) WithClientJar added in v0.0.18

func (c *Client) WithClientJar(jar http.CookieJar) ClientInterface

WithClientJar exp: jar, _ := cookiejar.New(nil) WithClientCookieJar(jar)

func (*Client) WithContentType

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

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

func (*Client) WithCookie

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

func (*Client) WithCookieMap added in v0.0.15

func (c *Client) WithCookieMap(cookies map[string]string) ClientInterface

func (*Client) WithCookieNextRequest added in v0.0.14

func (c *Client) WithCookieNextRequest(cache CacheInterface, ttl time.Duration) ClientInterface

WithCookieNextRequest

 The first access to the root domain name will cache cookie data, and the second access will carry the cookie data from the cache until the cache expires and is regenerated
	cache := requests.NewFileCache("you path/cache")
	WithCookieNextRequest(cache, time.Hour)

func (*Client) WithCookieString

func (c *Client) WithCookieString(cookieString string) ClientInterface

func (*Client) WithHeader

func (c *Client) WithHeader(k, v string) ClientInterface

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) WithHeaderMap added in v0.0.17

func (c *Client) WithHeaderMap(headers map[string]string) ClientInterface

WithHeaderMap 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) WithHeaderVerbatim

func (c *Client) WithHeaderVerbatim(k, v string) ClientInterface

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) WithProxyUrl

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

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) WithRandomMobileUserAgent added in v0.0.14

func (c *Client) WithRandomMobileUserAgent() ClientInterface

func (*Client) WithRandomUserAgent added in v0.0.14

func (c *Client) WithRandomUserAgent() ClientInterface

func (*Client) WithRedirectLimit

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

WithRedirectLimit limits the number of jumps.

func (*Client) WithRedirectPolicy

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

WithRedirectPolicy method sets the client redirect poilicy. 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) ClientInterface

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

func (*Client) WithToken

func (c *Client) WithToken(token string, authorizationType ...string) ClientInterface

WithToken Specify an authorization token for the request.

func (*Client) WithUserAgent

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

type ClientCallback added in v0.0.14

type ClientCallback func(client *Client) error

type ClientDoRequestInterface added in v0.0.17

type ClientDoRequestInterface interface {
	DoRequestUnmarshal(ctx context.Context, method string, uri string, data, d any) error
	DoRequestBytes(ctx context.Context, method string, uri string, data any) ([]byte, error)
	DoRequest(ctx context.Context, method, uri string, body any) (response *Response, err error)
}

type ClientFnInterface added in v0.0.17

type ClientFnInterface interface {
	SetJSONMarshaler(marshaler func(v interface{}) ([]byte, error)) ClientInterface
	SetJSONUnmarshaler(unmarshaler func(data []byte, v interface{}) error) ClientInterface
	SetXMLMarshaler(marshaler func(v any) ([]byte, error)) ClientInterface
	SetXMLUnmarshaler(unmarshaler func(data []byte, v any) error) ClientInterface
	Unmarshal(contentType string, b []byte, d any) (err error)

	OnBeforeRequest(callback ClientCallback) ClientInterface
	OnAfterRequest(callback RequestCallback) ClientInterface
	OnResponse(callback ResponseCallback) ClientInterface
	OnError(h ErrorHook) ClientInterface
	OnSuccess(h SuccessHook) ClientInterface
	OnPanic(h ErrorHook) ClientInterface
}

type ClientHeaderInterface added in v0.0.17

type ClientHeaderInterface interface {
	WithClientJar(jar http.CookieJar) ClientInterface
	WithHeader(header, value string) ClientInterface
	WithHeaderMap(headers map[string]string) ClientInterface
	WithHeaderVerbatim(header, value string) ClientInterface
	WithContentType(contentType string) ClientInterface
	WithUserAgent(userAgent string) ClientInterface
	WithRandomUserAgent() ClientInterface
	WithRandomMobileUserAgent() ClientInterface
	AsForm() ClientInterface
	AsJson() ClientInterface
	AsXml() ClientInterface
	WithBasicAuth(username, password string) ClientInterface
	WithToken(token string, tokenType ...string) ClientInterface

	WithCookieString(cookieString string) ClientInterface
	WithCookie(k, v string) ClientInterface
	WithCookieMap(cookies map[string]string) ClientInterface
	WithCookieNextRequest(cache CacheInterface, ttl time.Duration) ClientInterface

	WithRedirectPolicy(policies ...any) ClientInterface
	WithRedirectLimit(redirectLimit int) ClientInterface
}

type ClientHttpClientClient added in v0.0.17

type ClientHttpClientClient interface {
	SetHttpClient(client *http.Client) ClientInterface
	SetTimeout(t time.Duration) ClientInterface
	SetCheckRedirect(fn func(req *http.Request, via []*http.Request) error)
	SetTLSConfig(tlsConfig *tls.Config) ClientInterface
	WithProxyUrl(proxyURL string) ClientInterface
	WithTLSKeyCrt(crtFile, keyFile string) ClientInterface
}

type ClientInterface added in v0.0.17

type ClientInterface interface {
	ClientHttpClientClient
	ClientOwnerInterface
}

func New

func New() ClientInterface

func NewWithHttpClient added in v0.0.17

func NewWithHttpClient(client *http.Client) ClientInterface

type ClientMiddlewareInterface added in v0.0.17

type ClientMiddlewareInterface interface {
	Use(middlewares ...MiddlewareFunc) ClientInterface
}

type ClientOwnerInterface added in v0.0.17

type ClientOwnerInterface interface {
	Clone() ClientInterface
	SetDebug(debug bool) ClientInterface
	EnableDebug() ClientInterface
	EnableTrace() ClientInterface
	SetLogger(logger LoggerInterface) ClientInterface
	SetWriter(writer io.Writer) ClientInterface
	SetBaseURL(baseUrl string) ClientInterface
	SetQuery(query url.Values) ClientInterface
	SetCookie(cookie Cookie) ClientInterface
	SetHeader(header http.Header) ClientInterface
	SetRetry(retryCount int, retryWaitTime time.Duration) ClientInterface
	ClientFnInterface
	ClientMiddlewareInterface
	ClientHeaderInterface
	ClientRequestInterface
}

type ClientRequestInterface added in v0.0.17

type ClientRequestInterface interface {
	ClientDoRequestInterface
	Get(ctx context.Context, uri string, data any) (*Response, error)
	GetUnmarshal(ctx context.Context, uri string, data, d any) error
	GetBytes(ctx context.Context, uri string, data any) ([]byte, error)

	Put(ctx context.Context, uri string, data any) (*Response, error)
	PutUnmarshal(ctx context.Context, uri string, data, d any) error
	PutBytes(ctx context.Context, uri string, data any) ([]byte, error)

	Post(ctx context.Context, uri string, data any) (*Response, error)
	PostUnmarshal(ctx context.Context, uri string, data, d any) error
	PostBytes(ctx context.Context, uri string, data any) ([]byte, error)

	Delete(ctx context.Context, uri string, data any) (*Response, error)
	DeleteUnmarshal(ctx context.Context, uri string, data, d any) error
	DeleteBytes(ctx context.Context, uri string, data any) ([]byte, error)

	Head(ctx context.Context, uri string, data any) (*Response, error)
	HeadUnmarshal(ctx context.Context, uri string, data, d any) error
	HeadBytes(ctx context.Context, uri string, data any) ([]byte, error)

	Patch(ctx context.Context, uri string, data any) (*Response, error)
	PatchUnmarshal(ctx context.Context, uri string, data, d any) error
	PatchBytes(ctx context.Context, uri string, data any) ([]byte, error)

	Connect(ctx context.Context, uri string, data any) (*Response, error)
	ConnectUnmarshal(ctx context.Context, uri string, data, d any) error
	ConnectBytes(ctx context.Context, uri string, data any) ([]byte, error)

	Options(ctx context.Context, uri string, data any) (*Response, error)
	OptionsUnmarshal(ctx context.Context, uri string, data, d any) error
	OptionsBytes(ctx context.Context, uri string, data any) ([]byte, error)

	Trace(ctx context.Context, uri string, data any) (*Response, error)
	TraceUnmarshal(ctx context.Context, uri string, data, d any) error
	TraceBytes(ctx context.Context, uri string, data any) ([]byte, error)

	PostJson(ctx context.Context, uri string, data any) (*Response, error)
	PostJsonUnmarshal(ctx context.Context, uri string, data, d any) error
	PostJsonBytes(ctx context.Context, uri string, data any) ([]byte, error)

	PostForm(ctx context.Context, uri string, data url.Values) (*Response, error)
	PostFormUnmarshal(ctx context.Context, uri string, data url.Values, d any) error
	PostFormBytes(ctx context.Context, uri string, data url.Values) ([]byte, error)

	PostFormWithFiles(ctx context.Context, uri string, data url.Values) (*Response, error)
	PostFormWithFilesUnmarshal(ctx context.Context, uri string, data url.Values, d any) error
	PostFormWithFilesBytes(ctx context.Context, uri string, data url.Values) ([]byte, error)
}
type Cookie map[string][]string

func CookieStringEscape added in v0.0.15

func CookieStringEscape(cookie string) Cookie

func (Cookie) Add added in v0.0.13

func (v Cookie) Add(key, value string)

func (Cookie) Del added in v0.0.13

func (v Cookie) Del(key string)

func (Cookie) Encode added in v0.0.13

func (v Cookie) Encode() string

func (Cookie) Get added in v0.0.13

func (v Cookie) Get(key string) string

func (Cookie) Has added in v0.0.13

func (v Cookie) Has(key string) bool

func (Cookie) Set added in v0.0.13

func (v Cookie) Set(key, value string)

type CtxKeyString added in v0.0.18

type CtxKeyString string

type ErrorHook

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

type FileCache added in v0.0.8

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

func (*FileCache) CleanExpired added in v0.0.8

func (f *FileCache) CleanExpired()

func (*FileCache) Delete added in v0.0.8

func (f *FileCache) Delete(key string) error

func (*FileCache) Get added in v0.0.8

func (f *FileCache) Get(key string) (string, error)

func (*FileCache) Has added in v0.0.8

func (f *FileCache) Has(key string) bool

func (*FileCache) Set added in v0.0.8

func (f *FileCache) Set(key, value string, ttl time.Duration) error

type IRoute added in v0.0.6

type IRoute interface {
	GetMethod() string
	GetUri() string
	GetHeader() map[string]string
	GetTlsConfig() *tls.Config
	GetCookies() map[string]string
	GetBody() any
	GetD() any
}

type Logger added in v0.0.14

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

func DefaultLogger added in v0.0.14

func DefaultLogger() *Logger

func (*Logger) Debugf added in v0.0.14

func (l *Logger) Debugf(format string, v ...interface{})

func (*Logger) Errorf added in v0.0.14

func (l *Logger) Errorf(format string, v ...interface{})

func (*Logger) Warnf added in v0.0.14

func (l *Logger) Warnf(format string, v ...interface{})

type LoggerInterface added in v0.0.18

type LoggerInterface interface {
	Errorf(format string, v ...any)
	Warnf(format string, v ...any)
	Debugf(format string, v ...any)
}

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 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 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.

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 RequestCallback added in v0.0.14

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

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 ...ArgsFunc) (*Response, error)

func Delete

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

func Get

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

func Options

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

func Patch

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

func Post

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

func PostForm

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

func PostFormWithFiles added in v0.0.4

func PostFormWithFiles(uri string, data url.Values, args ...ArgsFunc) (*Response, error)

func PostJson

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

func Put

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

func Request

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

func Trace

func Trace(uri string, data any, args ...ArgsFunc) (*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() Cookie

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) ReadStream added in v0.0.5

func (r *Response) ReadStream(lineNumberFun func(line []byte, number int64)) int64

ReadStream Microsoft ChatGPT Data Structure start data: {"id":"","object":"","created":0,"model":"","prompt_filter_results":[{"prompt_index":0,"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":{"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"choices":[],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"role":"assistant"},"content_filter_results":{}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"我"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"是"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"一个"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual{"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"AI"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":{"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"助"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"手"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":","},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"可以"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual{"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"帮"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"助"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"您"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"查"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"找"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"信息"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual{"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":null,"delta":{"content":"。"},"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}],"usage":null} data: {"id":"chatcmpl-801dpnRDRT0u4Nx5tec615WTJOXJt","object":"chat.completion.chunk","created":1695017001,"model":"gpt-35-turbo","choices":[{"index":0,"finish_reason":"stop","delta":{},"content_filter_results":{}}],"usage":null} data: [DONE] Microsoft ChatGPT Data Structure end

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 ResponseCallback added in v0.0.14

type ResponseCallback func(client *Client, request *http.Request, response *Response) error

type ResponseError

type ResponseError struct {
	Response *Response
	Err      error
}

func (*ResponseError) Error

func (e *ResponseError) Error() string

type ResponseInterface added in v0.0.17

type ResponseInterface interface {
	Close() error
	TraceInfo() TraceInfo
	GetCookie() Cookie
	ReadAll() []byte
	ReadStream(lineNumberFun func(line []byte, number int64)) int64
	ReadAllString() string
	ContentType() string
	Unmarshal(d any) error
	IsSuccess() bool
	IsError() bool
}

type Route added in v0.0.6

type Route struct {
	Method, Uri     string
	Header, Cookies map[string]string
	TlsConfig       *tls.Config
	Body, D         any
}

func (*Route) GetBody added in v0.0.6

func (r *Route) GetBody() any

func (*Route) GetCookies added in v0.0.6

func (r *Route) GetCookies() map[string]string

func (*Route) GetD added in v0.0.6

func (r *Route) GetD() any

func (*Route) GetHeader added in v0.0.6

func (r *Route) GetHeader() map[string]string

func (*Route) GetMethod added in v0.0.6

func (r *Route) GetMethod() string

func (*Route) GetTlsConfig added in v0.0.6

func (r *Route) GetTlsConfig() *tls.Config

func (*Route) GetUri added in v0.0.6

func (r *Route) GetUri() 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
	// request execution flow, including retry count.
	RequestAttempt int
	// RemoteAddr returns the remote network address.
	RemoteAddr net.Addr
}

Jump to

Keyboard shortcuts

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