goreq

package module
v0.1.19 Latest Latest
Warning

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

Go to latest
Published: Sep 16, 2021 License: MIT Imports: 26 Imported by: 4

README

类似java的OKHttp的简单易用的HTTP客户端。

设计

逻辑图

三个核心概念:

  • Client

    提供可复用的通用逻辑封装,主要是两个方面:

    • httpclient的配置,如cookie,tls,超时,代理,body的编解码方式等
    • 通用逻辑封装,插件机制实现在请求前后对request和response做二次处理,比如认证,熔断,打印调用日志,设置api基础路径等,支持自定义插件开发。
  • Req

    request的封装,更方便的设置,使用与Client相同的插件,只是作用域不同。

  • Resp

    response的封装,提供各种方便的获取响应内容的方法。

应用场景

可以简单高效的解决如下常用使用场景:

  • 简单的调用一个接口地址并获取返回值
  • 调用api接口时需要补充认证相关的参数
  • 上传/下载文件
  • 调用api接口时,需要判断接口是否返回错误,并解析返回数据到struct
  • 调用api接口时,只是想获取返回内容的某一个字段的值,并不想构建struct
  • 调用时自动打印请求和响应内容
  • 熔断
  • opentracing
  • prometheus

安装

go get -u github.com/aiscrm/goreq

例子

简单例子

goreq.Get(ts.URL).Use(log.Dump()).Do().AsString()

TODO

  • prometheus

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNoTransport      = errors.New("req: no transport")
	ErrNoURL            = errors.New("req: url not specified")
	ErrLackParam        = errors.New("req: lack param")
	ErrNoParser         = errors.New("resp: no parser")
	ErrNoFileMatch      = errors.New("req: no file match")
	ErrNotSupportedBody = errors.New("req: not supported body")
	ErrNoUnmarshal      = errors.New("resp: no unmarshal")
	ErrNoMarshal        = errors.New("req: no marshal")
	ErrParseStruct      = errors.New("req: can not parse struct param")
	ErrBlocked          = errors.New("req: circuit breaker blocked")
)

define errors

View Source
var (
	DefaultClient = NewClient()
)

Functions

This section is empty.

Types

type Client

type Client interface {
	Init(...ClientOption) error
	Options() ClientOptions
	Use(...wrapper.CallWrapper) Client
	Do(*Req, ...ClientOption) *Resp
	New() *Req
	Get(rawURL string) *Req
	Post(rawURL string) *Req
}

func NewClient

func NewClient(opts ...ClientOption) Client

type ClientOption added in v0.1.16

type ClientOption func(options *ClientOptions)

func EnableCookie added in v0.1.16

func EnableCookie(enable bool) ClientOption

EnableCookie enable or disable cookie manager

func EnableInsecureTLS added in v0.1.16

func EnableInsecureTLS(enable bool) ClientOption

EnableInsecureTLS allows insecure https

func WithProxy added in v0.1.16

func WithProxy(proxy func(*http.Request) (*url.URL, error)) ClientOption

func WithProxyURL added in v0.1.16

func WithProxyURL(proxyURL string) ClientOption

func WithTLSCert added in v0.1.16

func WithTLSCert(certPEMBlock, keyPEMBlock []byte) ClientOption

func WithTimeout added in v0.1.16

func WithTimeout(timeout time.Duration) ClientOption

func WithTransport added in v0.1.16

func WithTransport(transport http.RoundTripper) ClientOption

type ClientOptions added in v0.1.16

type ClientOptions struct {
	EnableCookie          bool
	Timeout               time.Duration
	DialTimeout           time.Duration
	DialKeepAlive         time.Duration
	MaxIdleConns          int
	IdleConnTimeout       time.Duration
	TLSHandshakeTimeout   time.Duration
	ExpectContinueTimeout time.Duration
	Transport             http.RoundTripper
	TLSClientConfig       *tls.Config
	Proxy                 func(*http.Request) (*url.URL, error)
	Errors                []error
}

type Req

type Req struct {
	Request *http.Request
	Error   error
	// contains filtered or unexported fields
}

Req represents a http request

func Get

func Get(rawURL string) *Req

func New

func New() *Req

New return a empty request

func Post

func Post(rawURL string) *Req

Post return a post request

func (*Req) Clone

func (r *Req) Clone() *Req

func (*Req) Do

func (r *Req) Do() *Resp

Do is to call the request

func (*Req) GetBody

func (r *Req) GetBody() []byte

GetBody return request body

func (*Req) GetClient

func (r *Req) GetClient() Client

GetClient return client

func (*Req) GetContext

func (r *Req) GetContext() context.Context

GetContext return request context

func (*Req) Use

func (r *Req) Use(wrappers ...wrapper.CallWrapper) *Req

func (*Req) WithClient

func (r *Req) WithClient(c Client) *Req

WithClient with client

func (*Req) WithContext added in v0.1.16

func (r *Req) WithContext(ctx context.Context) *Req

func (*Req) WithFile added in v0.1.17

func (r *Req) WithFile(fieldName, fileName string, file io.ReadCloser) *Req

func (*Req) WithFileBytes added in v0.1.17

func (r *Req) WithFileBytes(fieldName, fileName string, data []byte) *Req

func (*Req) WithHeader added in v0.1.16

func (r *Req) WithHeader(key, value string) *Req

func (*Req) WithJSONBody added in v0.1.17

func (r *Req) WithJSONBody(data interface{}) *Req

func (*Req) WithMethod

func (r *Req) WithMethod(method string) *Req

func (*Req) WithURL

func (r *Req) WithURL(rawURL string) *Req

WithURL set request raw url

func (*Req) WithXMLBody added in v0.1.17

func (r *Req) WithXMLBody(data interface{}) *Req

type Resp

type Resp struct {
	Request  *http.Request
	Response *http.Response

	Error   error
	Cost    time.Duration
	Timeout bool
	// contains filtered or unexported fields
}

Resp represents a http response

func (*Resp) AsBytes

func (r *Resp) AsBytes() ([]byte, error)

AsBytes returns response body as []byte, return error if error happend when reading the response body

func (*Resp) AsFile

func (r *Resp) AsFile(dest string) error

AsFile save to file

func (*Resp) AsJSONMap

func (r *Resp) AsJSONMap() (map[string]interface{}, error)

func (*Resp) AsJSONStruct

func (r *Resp) AsJSONStruct(v interface{}) error

AsJSONStruct convert json response body to struct or map

func (*Resp) AsReader

func (r *Resp) AsReader() (io.Reader, error)

AsReader returns response body as reader

func (*Resp) AsString

func (r *Resp) AsString() (string, error)

AsString returns response body as string, return error if error happend when reading the response body

func (*Resp) AsStruct

func (r *Resp) AsStruct(v interface{}, unmarshal func([]byte, interface{}) error) error

AsStruct convert to struct. default to use json format

func (*Resp) AsXMLMap

func (r *Resp) AsXMLMap() (map[string]interface{}, error)

func (*Resp) AsXMLStruct

func (r *Resp) AsXMLStruct(v interface{}) error

AsXMLStruct convert xml response body to struct or map

func (*Resp) Bytes

func (r *Resp) Bytes() []byte

Bytes returns response body as []byte

func (*Resp) Consume

func (r *Resp) Consume(read bool)

Consume close response body

func (*Resp) ContentLength

func (r *Resp) ContentLength() int64

ContentLength returns content length

func (*Resp) ContentType

func (r *Resp) ContentType() string

ContentType returns content type

func (*Resp) StatusCode

func (r *Resp) StatusCode() int

StatusCode returns status code

func (*Resp) String

func (r *Resp) String() string

String returns response body as string

Directories

Path Synopsis
wechat Module
plugins
codec/sonic Module
encoding/br Module
prometheus Module
trace Module
vo module
log
url
prometheus Module
trace Module

Jump to

Keyboard shortcuts

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