axios

package module
v1.6.1 Latest Latest
Warning

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

Go to latest
Published: Dec 21, 2023 License: Apache-2.0 Imports: 21 Imported by: 12

README

go-axios

Build Status

简单易用的HTTP客户端,参考axios的相关实现,支持各类不同的interceptortransform,特性如下:

  • 支持自定义的transform,可根据应用场景指定各类不同的参数格式
  • 支持Request与Response的interceptor,可针对请求参数与响应数据添加各类的转换处理
  • 默认支持gzip与br两种压缩方式,节约带宽占用
  • 支持启用请求中的各事件记录,可细化请求的各场景耗时
  • 简单易用的Mock处理
  • Error与Done事件的支持,通过监听事件可快捷收集服务的出错与性能统计
// +build ignore

package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"time"

	"github.com/vicanso/go-axios"
)

func main() {
	// 使用默认的配置
	resp, err := axios.Get("https://www.baidu.com")
	if err != nil {
		panic(err)
	}
	fmt.Println(resp.Data)

	// 自定义instance,可指定client、interceptor等
	ins := axios.NewInstance(&axios.InstanceConfig{
		BaseURL:     "https://www.baidu.com",
		EnableTrace: true,
		Client: &http.Client{
			Transport: &http.Transport{
				Proxy: http.ProxyFromEnvironment,
			},
		},
		// 超时设置,建议设置此字段避免无接口无超时处理
		Timeout: 10 * time.Second,
		// OnDone 无论成功或失败均会调用,可在此处添加统计
		OnDone: func(config *axios.Config, resp *axios.Response, err error) {
			fmt.Println(config)
			fmt.Println(resp)
			fmt.Println(err)
		},
	})
	resp, err = ins.Get("/")
	if err != nil {
		panic(err)
	}
	buf, _ := json.Marshal(resp.Config.HTTPTrace.Stats())
	fmt.Println(resp.Config.HTTPTrace.Stats())
	fmt.Println(string(buf))
	fmt.Println(resp.Config.HTTPTrace.Protocol)
	fmt.Println(resp.Status)
	fmt.Println(string(resp.Data))
}

Documentation

Index

Constants

View Source
const (
	ErrCategoryDNS      = "dns"
	ErrCategoryTimeout  = "timeout"
	ErrCategoryCanceled = "canceled"
	ErrCategoryAddr     = "addr"
	ErrCategoryAborted  = "aborted"
	ErrCategoryRefused  = "refused"
	ErrCategoryReset    = "reset"
)
View Source
const (
	ResultSuccess = iota
	ResultFail
)
View Source
const (
	// UserAgent client user agent
	UserAgent = "go-axios/1.2.1"
)

Variables

View Source
var (
	// DefaultTransformResponse default transform response
	DefaultTransformResponse []TransformResponse
	// DefaultTransformRequest default transform request
	DefaultTransformRequest []TransformRequest
)
View Source
var ErrRequestDataTypeInvalid = errors.New("request data type is not supported")
View Source
var ErrRequestIsForbidden = errors.New("request is forbidden")
View Source
var ErrTooManyRequests = errors.New("too many request of the instance")

Functions

func GetInternalErrorCategory added in v1.3.0

func GetInternalErrorCategory(err error) string

GetInternalErrorCategory get the category of net op error

func MapToValues added in v1.4.0

func MapToValues(data map[string]string) url.Values

MapToValues converts map[string]string to url.Values

func MapToValuesOmitEmpty added in v1.4.0

func MapToValuesOmitEmpty(data map[string]string) url.Values

MapToValuesOmitEmpty converts map[string]string to url.Values, and omit empty value

func NewMultipartFile added in v1.4.0

func NewMultipartFile() *multipartFile

NewMultipartFile creates a multipart file writer

func ReadAllInitCap added in v1.4.2

func ReadAllInitCap(r io.Reader, initCap int) ([]byte, error)

copy from io.ReadAll ReadAll reads from r until an error or EOF and returns the data it read. A successful call returns err == nil, not err == EOF. Because ReadAll is defined to read from src until EOF, it does not treat an EOF from Read as an error to be reported.

func SetJSONMarshal added in v0.0.6

func SetJSONMarshal(fn JSONMarshal)

SetJSONMarshal set json marshal function

func SetJSONUnmarshal added in v0.0.6

func SetJSONUnmarshal(fn JSONUnmarshal)

SetJSONUnmarshal set json unmarshal function

Types

type Adapter

type Adapter func(config *Config) (resp *Response, err error)

Adapter adapter function

type BeforeNewRequestListeners added in v1.4.1

type BeforeNewRequestListeners []OnBeforeNewRequest

type Config

type Config struct {
	Request  *http.Request
	Response *Response
	// Route the request route
	Route string
	// URL the request url
	URL string
	// Method http request method, default is `get`
	Method string
	// BaseURL http request base url
	BaseURL string
	// TransformRequest transform request body
	TransformRequest []TransformRequest
	// TransformResponse transform response body
	TransformResponse []TransformResponse
	// Headers  custom headers for request
	Headers http.Header
	// Params params for request route
	Params map[string]string
	// Query query for request
	Query url.Values

	// Body the request body
	Body interface{}

	// Concurrency current amount handling request of instance
	Concurrency uint32

	// Timeout request timeout
	Timeout time.Duration

	// Context context
	Context context.Context

	// Client http client
	Client *http.Client
	// Adapter custom handling of request
	Adapter Adapter
	// RequestInterceptors request interceptor list
	RequestInterceptors []RequestInterceptor
	// ResponseInterceptors response interceptor list
	ResponseInterceptors []ResponseInterceptor

	// OnError on error function
	OnError OnError
	// OnDone on done event
	OnDone OnDone
	// OnBeforeNewRequest on request create event
	OnBeforeNewRequest OnBeforeNewRequest

	HTTPTrace *HT.HTTPTrace
	// contains filtered or unexported fields
}

Config http request config

func (*Config) AddBeforeNewRequestListener added in v1.4.1

func (bc *Config) AddBeforeNewRequestListener(listeners ...OnBeforeNewRequest)

func (*Config) AddDoneListener added in v1.4.1

func (bc *Config) AddDoneListener(listeners ...OnDone)

func (*Config) AddErrorListener added in v1.4.1

func (bc *Config) AddErrorListener(listeners ...OnError)

func (*Config) AddParam added in v0.1.6

func (conf *Config) AddParam(key, value string) *Config

AddParam add param

func (*Config) AddQuery added in v0.1.6

func (conf *Config) AddQuery(key, value string) *Config

AddQuery add query

func (*Config) AddQueryMap added in v0.2.1

func (conf *Config) AddQueryMap(query map[string]string) *Config

AddQueryMap convert map and add to query

func (*Config) AddQueryStruct added in v0.2.1

func (conf *Config) AddQueryStruct(value interface{}) (*Config, error)

AddQueryStruct convert struct and add to query

func (*Config) CURL added in v0.1.11

func (conf *Config) CURL() string

CURL convert config to curl

func (*Config) Get

func (conf *Config) Get(key string) interface{}

Get get value from config

func (*Config) GetBool

func (conf *Config) GetBool(key string) bool

GetBool get bool value

func (*Config) GetInt

func (conf *Config) GetInt(key string) int

GetInt get int value

func (*Config) GetString

func (conf *Config) GetString(key string) string

GetString get string value

func (*Config) GetURL added in v0.2.0

func (conf *Config) GetURL() string

GetURL generate the url of request config

func (*Config) PrependBeforeNewRequestListener added in v1.4.1

func (bc *Config) PrependBeforeNewRequestListener(listeners ...OnBeforeNewRequest)

func (*Config) PrependDoneListener added in v1.4.1

func (bc *Config) PrependDoneListener(listeners ...OnDone)

func (*Config) PrependErrorListener added in v1.4.1

func (bc *Config) PrependErrorListener(listeners ...OnError)

func (*Config) Set

func (conf *Config) Set(key string, value interface{})

Set set value to config

type CustomMocker added in v1.4.0

type CustomMocker func(*Config) (*Response, error)

type DoneListeners added in v1.4.1

type DoneListeners []OnDone

type ErrorListeners added in v1.4.1

type ErrorListeners []OnError

type Instance

type Instance struct {
	Config *InstanceConfig
	// contains filtered or unexported fields
}

Instance instance of axios

func GetDefaultInstance added in v0.0.5

func GetDefaultInstance() *Instance

GetDefaultInstance get default instance

func NewInstance

func NewInstance(config *InstanceConfig) *Instance

NewInstance create a new instance

func (*Instance) AppendRequestInterceptor added in v1.1.0

func (ins *Instance) AppendRequestInterceptor(fn RequestInterceptor)

AppendRequestInterceptor appends request interceptor to instance

func (*Instance) AppendResponseInterceptor added in v1.1.0

func (ins *Instance) AppendResponseInterceptor(fn ResponseInterceptor)

AppendResponseInterceptor appends response interceptor to instance

func (*Instance) CustomMock added in v1.4.0

func (ins *Instance) CustomMock(fn CustomMocker) (done func())

CustomMock sets custom mock response

func (*Instance) Delete

func (ins *Instance) Delete(url string, query ...url.Values) (resp *Response, err error)

Delete http delete request

func (*Instance) DeleteX added in v0.1.9

func (ins *Instance) DeleteX(context context.Context, url string, query ...url.Values) (resp *Response, err error)

DeleteX http delete request with context

func (*Instance) EnhanceDelete added in v0.1.8

func (ins *Instance) EnhanceDelete(result interface{}, url string, query ...url.Values) (err error)

EnhanceDelete http delete request and unmarshal response to struct

func (*Instance) EnhanceDeleteX added in v0.1.9

func (ins *Instance) EnhanceDeleteX(context context.Context, result interface{}, url string, query ...url.Values) (err error)

EnhanceDeleteX http delete request with context and unmarshal response to struct

func (*Instance) EnhanceGet added in v0.1.8

func (ins *Instance) EnhanceGet(result interface{}, url string, query ...url.Values) (err error)

EnhanceGetX http get request with context and unmarshal response to struct

func (*Instance) EnhanceGetX added in v0.1.9

func (ins *Instance) EnhanceGetX(context context.Context, result interface{}, url string, query ...url.Values) (err error)

EnhanceGetX http get request with context and unmarshal response to struct

func (*Instance) EnhancePatch added in v0.1.8

func (ins *Instance) EnhancePatch(result interface{}, url string, data interface{}, query ...url.Values) (err error)

EnhancePatch http patch request and unmarshal response to struct

func (*Instance) EnhancePatchX added in v0.1.9

func (ins *Instance) EnhancePatchX(context context.Context, result interface{}, url string, data interface{}, query ...url.Values) (err error)

EnhancePatchX http patch request with context and unmarshal response to struct

func (*Instance) EnhancePost added in v0.1.8

func (ins *Instance) EnhancePost(result interface{}, url string, data interface{}, query ...url.Values) (err error)

EnhancePost http post request and unmarshal response to struct

func (*Instance) EnhancePostX added in v0.1.9

func (ins *Instance) EnhancePostX(context context.Context, result interface{}, url string, data interface{}, query ...url.Values) (err error)

EnhancePostX http post request with context and unmarshal response to struct

func (*Instance) EnhancePut added in v0.1.8

func (ins *Instance) EnhancePut(result interface{}, url string, data interface{}, query ...url.Values) (err error)

EnhancePut http put request and unmarshal response to struct

func (*Instance) EnhancePutX added in v0.1.9

func (ins *Instance) EnhancePutX(context context.Context, result interface{}, url string, data interface{}, query ...url.Values) (err error)

EnhancePutX http put request with context and unmarshal response to struct

func (*Instance) EnhanceRequest added in v0.1.12

func (ins *Instance) EnhanceRequest(result interface{}, config *Config) (err error)

EnhanceRequest http request and unmarshal response to struct

func (*Instance) EnhanceUpload added in v1.4.0

func (ins *Instance) EnhanceUpload(result interface{}, url string, file *multipartFile, query ...url.Values) (err error)

EnhanceUpload uploads file and convert response to result

func (*Instance) EnhanceUploadX added in v1.4.0

func (ins *Instance) EnhanceUploadX(context context.Context, result interface{}, url string, file *multipartFile, query ...url.Values) (err error)

EnhanceUploadX uploads file with context and convert response to result

func (*Instance) Get

func (ins *Instance) Get(url string, query ...url.Values) (resp *Response, err error)

Get http get request

func (*Instance) GetConcurrency added in v0.1.17

func (ins *Instance) GetConcurrency() uint32

GetConcurrency get concurrency of instance

func (*Instance) GetX added in v0.1.9

func (ins *Instance) GetX(context context.Context, url string, query ...url.Values) (resp *Response, err error)

GetX http get request with context

func (*Instance) Head

func (ins *Instance) Head(url string, query ...url.Values) (resp *Response, err error)

Head http head request

func (*Instance) HeadX added in v0.1.9

func (ins *Instance) HeadX(context context.Context, url string, query ...url.Values) (resp *Response, err error)

HeadX http head request with context

func (*Instance) Mock added in v0.0.4

func (ins *Instance) Mock(resp *Response, interceptors ...RequestInterceptor) (done func())

Mock mock response

func (*Instance) MultiMock added in v0.1.0

func (ins *Instance) MultiMock(multi map[string]*Response, interceptors ...RequestInterceptor) (done func())

MultiMock multi mock response

func (*Instance) Options

func (ins *Instance) Options(url string, query ...url.Values) (resp *Response, err error)

Options http options request

func (*Instance) OptionsX added in v0.1.9

func (ins *Instance) OptionsX(context context.Context, url string, query ...url.Values) (resp *Response, err error)

OptionsX http options request with context

func (*Instance) Patch

func (ins *Instance) Patch(url string, data interface{}, query ...url.Values) (resp *Response, err error)

Patch http patch request

func (*Instance) PatchX added in v0.1.9

func (ins *Instance) PatchX(context context.Context, url string, data interface{}, query ...url.Values) (resp *Response, err error)

PatchX http patch request with context

func (*Instance) Post

func (ins *Instance) Post(url string, data interface{}, query ...url.Values) (resp *Response, err error)

Post http post request

func (*Instance) PostX added in v0.1.9

func (ins *Instance) PostX(context context.Context, url string, data interface{}, query ...url.Values) (resp *Response, err error)

PostX http post request with context

func (*Instance) PrependRequestInterceptor added in v1.1.0

func (ins *Instance) PrependRequestInterceptor(fn RequestInterceptor)

PrependRequestInterceptor prepends request interceptor to instance

func (*Instance) PrependResponseInterceptor added in v1.1.0

func (ins *Instance) PrependResponseInterceptor(fn ResponseInterceptor)

PrependResponseInterceptor prepends response interceptor to instance

func (*Instance) Put

func (ins *Instance) Put(url string, data interface{}, query ...url.Values) (resp *Response, err error)

Put http put request

func (*Instance) PutX added in v0.1.9

func (ins *Instance) PutX(context context.Context, url string, data interface{}, query ...url.Values) (resp *Response, err error)

PutX http put request with context

func (*Instance) Request

func (ins *Instance) Request(config *Config) (resp *Response, err error)

Request http request

func (*Instance) SetMaxConcurrency added in v1.2.0

func (ins *Instance) SetMaxConcurrency(value int32)

SetMaxConcurrency sets max concurrency for instance

func (*Instance) Upload added in v1.4.0

func (ins *Instance) Upload(url string, file *multipartFile, query ...url.Values) (resp *Response, err error)

Upload uploads file

func (*Instance) UploadX added in v1.4.0

func (ins *Instance) UploadX(context context.Context, url string, file *multipartFile, query ...url.Values) (resp *Response, err error)

UploadX uploads file with context

type InstanceConfig

type InstanceConfig struct {

	// BaseURL http request base url
	BaseURL string
	// TransformRequest transform request body
	TransformRequest []TransformRequest
	// TransformResponse transform response body
	TransformResponse []TransformResponse
	// Headers  custom headers for request
	Headers http.Header
	// Timeout request timeout
	Timeout time.Duration

	// Client http client
	Client *http.Client
	// Adapter custom adapter
	Adapter Adapter
	// MaxConcurrency max concurrency for instance
	// If lt 0, all request will be fail
	MaxConcurrency int32

	// RequestInterceptors request interceptor list
	RequestInterceptors []RequestInterceptor
	// ResponseInterceptors response interceptor list
	ResponseInterceptors []ResponseInterceptor

	// EnableTrace enable http trace
	EnableTrace bool
	// OnError on error function
	OnError OnError
	// OnDone on done event
	OnDone OnDone
	// OnBeforeNewRequest on request create event
	OnBeforeNewRequest OnBeforeNewRequest
	// contains filtered or unexported fields
}

InstanceConfig config of instance

func (*InstanceConfig) AddBeforeNewRequestListener added in v1.4.1

func (bc *InstanceConfig) AddBeforeNewRequestListener(listeners ...OnBeforeNewRequest)

func (*InstanceConfig) AddDoneListener added in v1.4.1

func (bc *InstanceConfig) AddDoneListener(listeners ...OnDone)

func (*InstanceConfig) AddErrorListener added in v1.4.1

func (bc *InstanceConfig) AddErrorListener(listeners ...OnError)

func (*InstanceConfig) PrependBeforeNewRequestListener added in v1.4.1

func (bc *InstanceConfig) PrependBeforeNewRequestListener(listeners ...OnBeforeNewRequest)

func (*InstanceConfig) PrependDoneListener added in v1.4.1

func (bc *InstanceConfig) PrependDoneListener(listeners ...OnDone)

func (*InstanceConfig) PrependErrorListener added in v1.4.1

func (bc *InstanceConfig) PrependErrorListener(listeners ...OnError)

type JSONMarshal added in v0.0.6

type JSONMarshal func(interface{}) ([]byte, error)

JSONMarshal json marshal function type

type JSONUnmarshal added in v0.0.6

type JSONUnmarshal func([]byte, interface{}) error

JSONUnmarshal json unmarshal function type

type OnBeforeNewRequest added in v0.1.15

type OnBeforeNewRequest func(config *Config) (err error)

OnBeforeNewRequest on request create event

type OnDone added in v0.0.6

type OnDone func(config *Config, resp *Response, err error)

OnDone on done event

type OnError

type OnError func(err error, config *Config) (newErr error)

OnError on error function

type RequestInterceptor

type RequestInterceptor func(config *Config) (err error)

RequestInterceptor request interceptor

type Response

type Response struct {
	UnmarshalData interface{}
	Data          []byte
	Status        int
	Headers       http.Header
	Config        *Config
	Request       *http.Request
	// OriginalResponse original http response
	OriginalResponse *http.Response
}

Response http response

func Delete added in v0.0.5

func Delete(url string, query ...url.Values) (resp *Response, err error)

Delete http delete request by default instance

func Get added in v0.0.5

func Get(url string, query ...url.Values) (resp *Response, err error)

Get http get request by default instance

func Head(url string, query ...url.Values) (resp *Response, err error)

Head http head request by default instance

func Options added in v0.0.5

func Options(url string, query ...url.Values) (resp *Response, err error)

Options http options request by default instance

func Patch added in v0.0.5

func Patch(url string, data interface{}, query ...url.Values) (resp *Response, err error)

Patch http patch request by default instance

func Post added in v0.0.5

func Post(url string, data interface{}, query ...url.Values) (resp *Response, err error)

Post http post request by default instance

func Put added in v0.0.5

func Put(url string, data interface{}, query ...url.Values) (resp *Response, err error)

Put http put request by default instance

func Request added in v0.0.5

func Request(config *Config) (resp *Response, err error)

Request http request by default instance

func Upload added in v1.4.0

func Upload(url string, file *multipartFile, query ...url.Values) (resp *Response, err error)

Upload upload file by default instance

func (*Response) JSON

func (resp *Response) JSON(v interface{}) (err error)

JSON convert json data

type ResponseInterceptor

type ResponseInterceptor func(resp *Response) (err error)

ResponseInterceptor response interceptor

type Stats added in v1.3.0

type Stats struct {
	Route               string `json:"route,omitempty"`
	Method              string `json:"method,omitempty"`
	Result              int    `json:"result,omitempty"`
	URI                 string `json:"uri,omitempty"`
	Status              int    `json:"status,omitempty"`
	Reused              bool   `json:"reused,omitempty"`
	DNSCoalesced        bool   `json:"dnsCoalesced"`
	Addr                string `json:"addr,omitempty"`
	Use                 int    `json:"use,omitempty"`
	DNSUse              int    `json:"dnsUse,omitempty"`
	TCPUse              int    `json:"tcpUse,omitempty"`
	TLSUse              int    `json:"tlsUse,omitempty"`
	RequestSendUse      int    `json:"requestSendUse"`
	ServerProcessingUse int    `json:"serverProcessingUse,omitempty"`
	ContentTransferUse  int    `json:"contentTransferUse,omitempty"`
	Size                int    `json:"size,omitempty"`
}

func GetStats added in v1.3.0

func GetStats(conf *Config, err error) (stats Stats)

GetStats get stats of request

type TransformRequest

type TransformRequest func(body interface{}, headers http.Header) (data interface{}, err error)

TransformRequest transform function for http request

type TransformResponse

type TransformResponse func(body []byte, headers http.Header) (data []byte, err error)

TransformResponse transform function for http response

Jump to

Keyboard shortcuts

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