hasaki

package module
v1.7.3 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2026 License: MIT Imports: 14 Imported by: 4 modules, 4 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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)

Base URL

You can set a base URL for all requests made by the client.

// Create a client with base URL
cli, _ := hasaki.NewClient(hasaki.WithBaseURL("https://api.example.com"))

// GET https://api.example.com/users
resp := cli.Get("/users").Send(nil)

// GET https://api.example.com/api/v1/products
resp := cli.Get("/api/v1/products").Send(nil)

Documentation

Index

Constants

View Source
const (
	// MimeJson JSON MIME类型
	// JSON MIME type
	MimeJson = "application/json;charset=utf-8"
	// MimeYaml YAML MIME类型
	// YAML MIME type
	MimeYaml = "application/x-yaml;charset=utf-8"
	// MimeXml XML MIME类型
	// XML MIME type
	MimeXml = "application/xml;charset=utf-8"
	// MimeProtoBuf Protobuf MIME类型
	// Protobuf MIME type
	MimeProtoBuf = "application/x-protobuf"
	// MimeForm 表单 MIME类型
	// Form MIME type
	MimeForm = "application/x-www-form-urlencoded"
	// MimeStream 流式 MIME类型
	// Stream MIME type
	MimeStream = "application/octet-stream"
	// MimeJpeg JPEG图片 MIME类型
	// JPEG image MIME type
	MimeJpeg = "image/jpeg"
	// MimeGif GIF图片 MIME类型
	// GIF image MIME type
	MimeGif = "image/gif"
	// MimePng PNG图片 MIME类型
	// PNG image MIME type
	MimePng = "image/png"
	// MimeMp4 MP4视频 MIME类型
	// MP4 video MIME type
	MimeMp4 = "video/mpeg4"
)

Variables

View Source
var (
	// JsonCodec JSON编解码器
	// JSON codec
	JsonCodec = new(jsonCodec)
	// FormCodec 表单编解码器
	// Form codec
	FormCodec = new(formCodec)
	// XmlCodec XML编解码器
	// XML codec
	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)

AfterFunc 请求后中间件函数类型 Post-request middleware function type

type Any added in v1.0.4

type Any map[string]any

Any 通用类型映射 Generic type map

type BeforeFunc added in v1.5.0

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

BeforeFunc 请求前中间件函数类型 Pre-request middleware function type

type BytesReadCloser added in v1.6.6

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

type Client

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

Client HTTP客户端 HTTP client

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

Delete 发送DELETE请求 Send DELETE request

func (*Client) Get added in v1.2.0

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

Get 发送GET请求 Send GET request

func (*Client) Head added in v1.6.5

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

Head 发送HEAD请求 Send HEAD request

func (*Client) Options added in v1.6.5

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

Options 发送OPTIONS请求 Send OPTIONS request

func (*Client) Patch added in v1.6.5

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

Patch 发送PATCH请求 Send PATCH request

func (*Client) Post added in v1.2.0

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

Post 发送POST请求 Send POST request

func (*Client) Put added in v1.2.0

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

Put 发送PUT请求 Send PUT request

func (*Client) Request added in v1.4.0

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

Request 创建HTTP请求 Create HTTP request

type Codec added in v1.7.0

type Codec interface {
	Encoder
	Decoder
}

Codec 编解码器接口,同时包含编码和解码功能 Codec interface, includes both encoding and decoding functionality

type Decoder added in v1.7.0

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

Decoder 解码器接口 Decoder interface

type Encoder added in v1.3.0

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

Encoder 编码器接口 Encoder interface

func NewStreamEncoder added in v1.6.1

func NewStreamEncoder(contentType string) Encoder

NewStreamEncoder 创建流式编码器 Create a stream 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 WithBaseURL added in v1.7.2

func WithBaseURL(baseURL string) Option

WithBaseURL 设置基础URL; 所有请求的URL都会与BaseURL拼接 Setting the base URL; all request URLs will be concatenated with the BaseURL

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
}

Request HTTP请求结构体 HTTP request struct

func Delete

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

Delete 发送DELETE请求 Send DELETE request

func Get

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

Get 发送GET请求 Send GET request

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

Head 发送HEAD请求 Send HEAD 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

Options 发送OPTIONS请求 Send OPTIONS request

func Patch added in v1.6.5

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

Patch 发送PATCH请求 Send PATCH request

func Post

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

Post 发送POST请求 Send POST request

func Put

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

Put 发送PUT请求 Send PUT 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
}

Response HTTP响应结构体 HTTP response struct

func (*Response) Bind added in v1.6.3

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

Bind 使用指定的解码器将响应体绑定到目标对象 Bind response body to target object using specified decoder

func (*Response) BindForm added in v1.6.5

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

BindForm 将响应体绑定为表单格式 Bind response body as form

func (*Response) BindJSON added in v1.0.5

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

BindJSON 将响应体绑定为JSON格式 Bind response body as JSON

func (*Response) BindXML added in v1.6.5

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

BindXML 将响应体绑定为XML格式 Bind response body as XML

func (*Response) Context added in v1.4.2

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

Context 返回响应上下文 Return response context

func (*Response) Err added in v1.0.5

func (c *Response) Err() error

Err 返回响应错误 Return response error

func (*Response) ReadBody added in v1.6.0

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

ReadBody 读取响应体 Read response body

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
⌂ 换网址