hihttp

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2022 License: MIT Imports: 10 Imported by: 0

README

介绍

该库对Go原生http库做了封装,添加了错误处理,超时处理及重试功能。

Todo

  • 错误处理;
  • 超时处理;
  • 重试功能;
  • 错误回调;
  • GET、POST支持;
  • DELETE、PUT、PATCH支持;

全局参数设置

hihttp.Load(
	hihttp.WithTimeout(time.Second), // 设置全局超时时间
	hihttp.WithRetryCount(1), // 设置全局重试次数
	hihttp.WithRetryWait(time.Second),// 设置全局重试等待时间
	// 设置全局重试错误时的回调方法
	hihttp.WithRetryError(func(ctx context.Context, r hihttp.Request) error {
		return nil
	}),
)

GET示例

// 正常发送一个Get请求
res, err := hihttp.New().Get(context.Background(), "http://www.google.com")
if err != nil {
	fmt.Println(err)
}

// 添加header和cookie
hihttp.New().SetHeader("token", "1234567890").SetCookies(&http.Cookie{
			Name:  "token",
			Value: "abcdefg",
	}).Get(context.Background(), "http://www.google.com")


// 正常发送一个Get请求,追加get参数,以key-value格式
res, err := hihttp.New().Get(context.Background(), "http://www.google.com",hihttp.NewKVParam("name", "jankin"))
if err != nil {
	fmt.Println(err)
}

// 正常发送一个Get请求,追加get参数,以map格式
res, err := hihttp.New().Get(context.Background(), "http://www.google.com",hihttp.NewMapParams(map[string]interface{}{
		"name": "jankin",
	}))
if err != nil {
	fmt.Println(err)
}

// 正常发送一个Get请求,追加get参数,以字符串格式
res, err := hihttp.New().Get(context.Background(), "http://www.google.com",hihttp.NewQueryParam("name=jankin"))
if err != nil {
	fmt.Println(err)
}

POST 示例

// -- application/x-www-form-urlencoded -- // 
// 以map的形式添加post参数
hihttp.New().Post(context.Background(), "http://www.yumontime.com/test/login",hihttp.NewWWWFormPayload(map[string]interface{}{
		"username": "jankin",
	}))


// -- application/json -- //
hihttp.New().SetHeader(hihttp.SerializationType,hihttp.SerializationTypeJSON).Post(context.Background(), "http://www.yumontime.com/test/login", hihttp.NewJSONPayload("username=jankin"))

超时处理

hihttp共有两种方式可以实现超时处理,具体说明和使用方式如下所示

  1. hihttp.WithTimeout(time.Second)
res, err := New(WithTimeout(time.Second)).Get(ctx, urlStr)
  1. 在Get、Post等方法里传入一个带有timeout的context
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
res, err := New(WithTimeout(6*time.Second)).Get(ctx, urlStr)
注意:第二种方式的优先级将优于第一种,也就是说如果两种方式同时在使用,则以传入ctx的时间为实际超时时间。

请求重试

hihttp集成了请求重试,如果在请求失败(含请求超时)后,可以进行请求重试,即在延时一段时间后(可以是0秒),重新发起请求。

urlStr := "https://www.google.com"
// 请求失败后会再次进行重试请求
ctx := context.Background()
res1, err := New(WithRetryCount(2)).Get(ctx, urlStr)
if err != nil {
	t.Error(err)
}
t.Log(string(res1))

Documentation

Index

Constants

View Source
const (
	// MethodGet HTTP method
	GET = "GET"
	// MethodPost HTTP method
	POST = "POST"
	// MethodPut HTTP method
	PUT = "PUT"
	// MethodDelete HTTP method
	DELETE = "DELETE"
	// MethodDelete HTTP method
	PATCH = "PATCH"
)
View Source
const (
	SerializationType          string = "Content-Type"
	SerializationTypeFormData  string = "multipart/form-data"
	SerializationTypeJSON      string = "application/json"
	SerializationTypeWWWFrom   string = "application/x-www-form-urlencoded"
	SerializationTypePlainText string = "text/plain; charset=utf-8"
)

Variables

This section is empty.

Functions

func Load

func Load(opts ...Option)

Load 设置client的全局参数

func NewFormPayload

func NewFormPayload(data map[string]interface{}) *formPayload

NewFormPayload 会根据序列化类型,生成一个payload Content-Type = multipart/form-data

func NewJSONPayload

func NewJSONPayload(data interface{}) *jsonPayload

NewJSONPayload 会根据序列化类型,生成一个payload Content-Type = application/json

func NewKVParam

func NewKVParam(key string, value interface{}) *kvParam

func NewMapParams

func NewMapParams(m map[string]interface{}) *mapParams

func NewQueryParam

func NewQueryParam(query string) *queryParam

func NewWWWFormPayload

func NewWWWFormPayload(data map[string]interface{}) *wwwFormPayload

NewWWWFormPayload 会根据序列化类型,生成一个payload Content-Type = application/x-www-form-urlencoded

Types

type HiHTTP

type HiHTTP interface {
	Get(ctx context.Context, urlStr string, data ...Param) ([]byte, error)
	Post(ctx context.Context, urlStr string, p Payload) ([]byte, error)
	Put(ctx context.Context, urlStr string, p Payload) ([]byte, error)
	Delete(ctx context.Context, urlStr string, data ...Param) ([]byte, error)
	Patch(ctx context.Context, urlStr string, p Payload) ([]byte, error)
}

type Option

type Option func(*Options)

func WithRetryCount

func WithRetryCount(retryCount int) Option

func WithRetryError

func WithRetryError(retryError RetryErrorFunc) Option

func WithRetryWait

func WithRetryWait(retryWait time.Duration) Option

func WithTimeout

func WithTimeout(timeout time.Duration) Option

type Options

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

Options 几个公共参数

type Param

type Param interface {
	Marshal() string
}

type Payload

type Payload interface {
	Serialize() io.Reader
	ContentType() string
}

type Request

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

func New

func New(opts ...Option) *Request

New 设置公共参数

func (*Request) Delete

func (r *Request) Delete(ctx context.Context, urlStr string, data ...Param) ([]byte, error)

Delete 发送一个delete请求

func (*Request) Get

func (r *Request) Get(ctx context.Context, urlStr string, data ...Param) ([]byte, error)

Get 发送一个Get请求 也可以把参数直接放到URL后面,则data不传即可

func (*Request) Patch

func (r *Request) Patch(ctx context.Context, urlStr string, p Payload) ([]byte, error)

Patch 发送patch请求

func (*Request) Post

func (r *Request) Post(ctx context.Context, urlStr string, p Payload) ([]byte, error)

Post 发送一个POST请求

func (*Request) Put

func (r *Request) Put(ctx context.Context, urlStr string, p Payload) ([]byte, error)

Put 发送Put请求

func (*Request) SetCookies

func (r *Request) SetCookies(hc ...*http.Cookie) *Request

SetCookies 设置cookie

func (*Request) SetHeader

func (r *Request) SetHeader(key, value string) *Request

SetHeader 以k-v格式设置header

func (*Request) SetHeaders

func (r *Request) SetHeaders(args map[string]string) *Request

SetHeaders 设置header参数 map[string]string{} 例如: c.Headers(map[string]string{"key":"value"})

type RetryErrorFunc

type RetryErrorFunc func(ctx context.Context, r *Request) error

Jump to

Keyboard shortcuts

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