hhttp

package module
v0.0.0-...-f2307b1 Latest Latest
Warning

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

Go to latest
Published: May 5, 2023 License: MIT Imports: 10 Imported by: 0

README

hhttp一个为了方便而生的Go语言http client

关于为什么是h开头?

  • 可以是我的姓氏(侯)的第一个字母;
  • 可以是我们学变成的第一个程序hello ,world的第一个字母;
  • 也可以是hello、hi;
  • ……

1 介绍

该库对Go原生http库做了封装,添加了错误处理,超时处理及重试功能。为了实现更快捷、更方便的使用Go的http client发送请求。

推荐使用Go1.18及以上版本。

2 主要功能

  • GET、POST、DELETE、PUT、PATCH支持;
  • 错误处理、错误回调;
  • 超时处理;
  • 重试功能;
  • 自定义header和cookie;
  • 友好的支持文件上传和下载;
  • ……

3 基本使用

3.1 全局参数设置

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

3.2 GET示例

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

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


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

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

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

3.3 POST 示例

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


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

3.4 超时处理

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

  1. hhttp.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的时间为实际超时时间。

特别说明,Go的http.Client的timeout的优先级会大于通过context设置的超时时间,因此此处说明的是只是通过context设置的超时时间。

默认的http.Client的超时时间设置的是30秒,默认的context的超时时间是5秒。一般情况下只需要按照上面的修改context的超时时间即可。如果超时时间的需求可能会超过30秒,可通过如下修改来实现

New().SetTimeout(time.Minute)

3.5请求重试

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

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

4 支持

在使用过程中有任何问题,欢迎在Issues里留言互动, 也欢迎您能指出项目存在的问题。

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 常见在表单的文件上传
	SerializationTypeFormData string = "multipart/form-data"

	SerializationTypeJSON    string = "application/json"
	SerializationTypeWWWFrom string = "application/x-www-form-urlencoded"

	// SerializationTypePlainText 用于请求和响应文本数据。
	SerializationTypePlainText string = "text/plain; charset=utf-8"
	// SerializationTypeImageGIF gif图片
	SerializationTypeImageGIF string = "image/gif"
	// SerializationTypeImageJPEG jpeg图片
	SerializationTypeImageJPEG string = "image/jpeg"
	// SerializationTypeImagePNG png图片
	SerializationTypeImagePNG string = "image/png"
)

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 Header map[string][]string

type HiHTTP

type HiHTTP interface {
	Get(ctx context.Context, urlStr string, data ...Param) (*Response, error)
	Post(ctx context.Context, urlStr string, p Payload) (*Response, error)
	Put(ctx context.Context, urlStr string, p Payload) (*Response, error)
	Delete(ctx context.Context, urlStr string, data ...Param) (*Response, error)
	Patch(ctx context.Context, urlStr string, p Payload) (*Response, 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) (*Response, error)

Delete 发送一个delete请求

func (*Request) Get

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

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

func (*Request) Patch

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

Patch 发送patch请求

func (*Request) Post

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

Post 发送一个POST请求

func (*Request) Put

func (r *Request) Put(ctx context.Context, urlStr string, p Payload) (*Response, 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(headers Header) *Request

SetHeaders 设置header参数 Header 例如: c.Headers(header)

func (*Request) SetTimeout

func (r *Request) SetTimeout(t time.Duration) *Request

SetTimeout 修改http.Client的超时时间,该超时时间默认是30s,优先级大于通过context设置的超时时间

type Response

type Response struct {
	Status     string // e.g. "200 OK"
	StatusCode int    // e.g. 200
	Proto      string // e.g. "HTTP/1.0"
	// ProtoMajor      int    // e.g. 1
	// ProtoMinor      int    // e.g. 0
	Header Header
	Body   []byte
	// ContentLength   int64
	Close           bool
	RequestDuration time.Duration
}

func (*Response) BodyString

func (r *Response) BodyString() string

BodyString 直接返回一个string格式的body

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