hasaki

package module
v1.7.1 Latest Latest
Warning

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

Go to latest
Published: Mar 22, 2024 License: MIT Imports: 14 Imported by: 4

README

Hasaki

HTTP Request Library for Go
logo

go-test codecov

Features

  • Buffer Pool
  • Trace the Error Stack
  • Build-In JSON / XML / WWWForm / Protobuf / YAML Codec
  • Request Before and After Middleware
  • Export cURL Command in Debug Mode

Install

go get -v github.com/lxzan/hasaki

Usage

Get

// GET https://api.example.com/search
// Send get request with path parameters. Turn on data compression.

resp := hasaki.
    Get("https://api.example.com/%s", "search").
    SetHeader("Accept-Encoding", "gzip, deflate").
    Send(nil)
// GET https://api.example.com/search?q=hasaki&page=1
// Send get request, with Query parameter, encoded with url.Values

resp := hasaki.
    Get("https://api.example.com/search").
    SetQuery(url.Values{
      "q":    []string{"hasaki"},
      "page": []string{"1"},
    }).
    Send(nil)

Post

// POST https://api.example.com/search
// Send post request, encoded with json

type Req struct {
    Q    string `json:"q"`
    Page int    `json:"page"`
}
resp := hasaki.
    Post("https://api.example.com/search").
    Send(Req{
        Q:    "hasaki",
        Page: 1,
    })
// POST https://api.example.com/search
// Send post request, encoded with www-form

resp := hasaki.
    Post("https://api.example.com/search").
    SetEncoder(hasaki.FormEncoder).
    Send(url.Values{
        "q":    []string{"hasaki"},
        "page": []string{"1"},
    })

Stream

// POST https://api.example.com/upload
// Send a put request, using a byte stream

var reader io.Reader
encoder := hasaki.NewStreamEncoder(hasaki.MimeStream)
resp := hasaki.
    Put("https://api.example.com/upload").
    SetEncoder(encoder).
    Send(reader)

Error Stack

// Print the error stack
data := make(map[string]any)
err := hasaki.
    Post("https://api.example.com/upload").
    Send(nil).
    BindJSON(&data)
if err != nil {
    log.Printf("%+v", err)
}

Middleware

Very useful middleware, you can use it to do something before and after the request is sent.

The middleware is a function, it receives a context and a request or response object, and returns a context and an error.

Under code is a simple middleware example , record the request latency.

// You can use the before and after middleware to do something before and after the request is sent

before := hasaki.WithBefore(func(ctx context.Context, request *http.Request) (context.Context, error) {
    return context.WithValue(ctx, "t0", time.Now()), nil
})

after := hasaki.WithAfter(func(ctx context.Context, response *http.Response) (context.Context, error) {
    t0 := ctx.Value("t0").(time.Time)
    log.Printf("latency=%s", time.Since(t0).String())
    return ctx, nil
})

var url = "https://api.github.com/search/repositories"
cli, _ := hasaki.NewClient(before, after)
cli.Get(url).Send(nil)

Documentation

Index

Constants

View Source
const (
	MimeJson     = "application/json;charset=utf-8"
	MimeYaml     = "application/x-yaml;charset=utf-8"
	MimeXml      = "application/xml;charset=utf-8"
	MimeProtoBuf = "application/x-protobuf"
	MimeForm     = "application/x-www-form-urlencoded"
	MimeStream   = "application/octet-stream"
	MimeJpeg     = "image/jpeg"
	MimeGif      = "image/gif"
	MimePng      = "image/png"
	MimeMp4      = "video/mpeg4"
)

Variables

View Source
var (
	JsonCodec = new(jsonCodec)
	FormCodec = new(formCodec)
	XmlCodec  = new(xmlCodec)
)

Functions

func SetClient added in v1.6.0

func SetClient(c *Client)

SetClient 设置全局客户端 Setting the global client

Types

type AfterFunc added in v1.5.0

type AfterFunc func(ctx context.Context, response *http.Response) (context.Context, error)

type Any added in v1.0.4

type Any map[string]any

type BeforeFunc added in v1.5.0

type BeforeFunc func(ctx context.Context, request *http.Request) (context.Context, error)

type BytesReadCloser added in v1.6.6

type BytesReadCloser interface {
	io.ReadCloser
	Bytes() []byte
}

type Client

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

func NewClient added in v1.2.0

func NewClient(options ...Option) (*Client, error)

NewClient 新建一个客户端 Create a new client

func (*Client) Delete added in v1.2.0

func (c *Client) Delete(url string, args ...any) *Request

func (*Client) Get added in v1.2.0

func (c *Client) Get(url string, args ...any) *Request

func (*Client) Head added in v1.6.5

func (c *Client) Head(url string, args ...any) *Request

func (*Client) Options added in v1.6.5

func (c *Client) Options(url string, args ...any) *Request

func (*Client) Patch added in v1.6.5

func (c *Client) Patch(url string, args ...any) *Request

func (*Client) Post added in v1.2.0

func (c *Client) Post(url string, args ...any) *Request

func (*Client) Put added in v1.2.0

func (c *Client) Put(url string, args ...any) *Request

func (*Client) Request added in v1.4.0

func (c *Client) Request(method string, url string, args ...any) *Request

type Codec added in v1.7.0

type Codec interface {
	Encoder
	Decoder
}

type Decoder added in v1.7.0

type Decoder interface {
	Decode(r io.Reader, v any) error
}

type Encoder added in v1.3.0

type Encoder interface {
	Encode(v any) (io.Reader, error)
	ContentType() string
}

func NewStreamEncoder added in v1.6.1

func NewStreamEncoder(contentType string) Encoder

type Option added in v1.5.0

type Option func(c *config)

func WithAfter added in v1.5.0

func WithAfter(fn AfterFunc) Option

WithAfter 设置请求后中间件 Setting up post-request middleware

func WithBefore added in v1.5.0

func WithBefore(fn BeforeFunc) Option

WithBefore 设置请求前中间件 Setting up pre-request middleware

func WithHTTPClient added in v1.6.0

func WithHTTPClient(client *http.Client) Option

WithHTTPClient 设置HTTP客户端 Setting the HTTP client

func WithReuseBody added in v1.6.6

func WithReuseBody() Option

WithReuseBody 开启Body可重复读; Response.Body可以被断言为BytesReadCloser, 调用Bytes()方法重复读取. Turn on Body repeatable read; Response.Body can be asserted as BytesReadCloser, call Bytes() method to repeat reads.

type Request

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

func Delete

func Delete(url string, args ...any) *Request

func Get

func Get(url string, args ...any) *Request
func Head(url string, args ...any) *Request

func NewRequest added in v1.0.3

func NewRequest(method string, url string, args ...any) *Request

NewRequest 新建一个请求 Create a new request

func Options added in v1.2.0

func Options(url string, args ...any) *Request

func Patch added in v1.6.5

func Patch(url string, args ...any) *Request

func Post

func Post(url string, args ...any) *Request

func Put

func Put(url string, args ...any) *Request

func (*Request) Debug added in v1.6.4

func (c *Request) Debug() *Request

Debug 开启调试模式, 打印CURL命令 Enable debug mode, print CURL commands

func (*Request) Send added in v1.0.3

func (c *Request) Send(body any) *Response

Send 发送请求 Send http request

func (*Request) SetAfter added in v1.6.2

func (c *Request) SetAfter(f AfterFunc) *Request

SetAfter 设置请求后中间件 Setting up post-request middleware

func (*Request) SetBefore added in v1.6.2

func (c *Request) SetBefore(f BeforeFunc) *Request

SetBefore 设置请求前中间件 Setting up pre-request middleware

func (*Request) SetContext added in v1.4.0

func (c *Request) SetContext(ctx context.Context) *Request

SetContext 设置请求上下文 Set Request context

func (*Request) SetEncoder added in v1.3.0

func (c *Request) SetEncoder(encoder Encoder) *Request

SetEncoder 设置编码器 Set request body encoder

func (*Request) SetHeader added in v1.4.0

func (c *Request) SetHeader(k, v string) *Request

SetHeader 设置请求头 Set Request Header

func (*Request) SetHeaders added in v1.2.0

func (c *Request) SetHeaders(headers http.Header) *Request

SetHeaders 批量设置请求头 Set Request Header

func (*Request) SetQuery added in v1.4.0

func (c *Request) SetQuery(query any) *Request

SetQuery 设置查询参数, 详情请参考 https://github.com/go-playground/form To set the query parameters, please refer to https://github.com/go-playground/form for details.

type Response added in v1.0.3

type Response struct {
	*http.Response
	// contains filtered or unexported fields
}

func (*Response) Bind added in v1.6.3

func (c *Response) Bind(v any, decoder Decoder) error

func (*Response) BindForm added in v1.6.5

func (c *Response) BindForm(v *url.Values) error

func (*Response) BindJSON added in v1.0.5

func (c *Response) BindJSON(v any) error

func (*Response) BindXML added in v1.6.5

func (c *Response) BindXML(v any) error

func (*Response) Context added in v1.4.2

func (c *Response) Context() context.Context

func (*Response) Err added in v1.0.5

func (c *Response) Err() error

func (*Response) ReadBody added in v1.6.0

func (c *Response) ReadBody() ([]byte, error)

Directories

Path Synopsis
contrib
pb Module
yaml Module

Jump to

Keyboard shortcuts

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