greq

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Jun 24, 2026 License: MIT Imports: 21 Imported by: 0

README

greq

GitHub go.mod Go version GitHub tag (latest SemVer) GoDoc Go Report Card Unit-Tests Coverage Status

中文说明 | English

greq is a small, composable HTTP client for Go — a chainable request builder, pluggable middleware, retry, batch, file upload/download, and bundled CLI tools (greq, gbench).

Features

  • Chainable request builder for GET / POST / PUT / PATCH / DELETE / HEAD
  • Pluggable middleware chain
  • Pluggable body providers (raw, JSON, form, multipart) and response decoders (JSON, XML)
  • Configurable retry with default checker (network errors, 5xx, 429) and per-request override
  • Batch concurrent requests with ExecuteAll / ExecuteAny semantics (ext/batch)
  • Upload / download helpers — single file, multi-file, multipart with form fields
  • Parse and send IDE .http file request format directly (ext/httpfile)
  • BeforeSend / AfterSend hooks and pluggable Doer for testing
  • Bundled CLI tools:
    • cmd/greq — curl-like HTTP client that understands .http files
    • cmd/gbenchab-like benchmark tool with progress bar and graceful Ctrl+C

Install

Library
go get github.com/gookit/greq
CLI tools

Install by Eget:

eget install gookit/greq
eget install --name gbench gookit/greq

Install by Go:

# HTTP request tool
go install github.com/gookit/greq/cmd/greq@latest
# HTTP benchmark tool
go install github.com/gookit/greq/cmd/gbench@latest

Quick start

package main

import (
    "fmt"

    "github.com/gookit/greq"
)

func main() {
    resp, err := greq.New("https://httpbin.org").
        JSONType().
        UserAgent("custom-client/1.0").
        PostDo("/post", `{"name": "inhere"}`)
    if err != nil {
        panic(err)
    }

    var ret map[string]any
    if err := resp.Decode(&ret); err != nil {
        panic(err)
    }
    fmt.Printf("%+v\n", ret)
}

For one-off calls there are package-level shortcuts that share a default client:

resp, _ := greq.GetDo("https://httpbin.org/get")
_, _ = greq.PostDo("https://httpbin.org/post", `{"key":"val"}`)

Building requests

greq.New(baseURL) returns a *Client. Calling any chainable method on the client (JSONType, UserAgent, Get, …) returns a *Builder you can keep configuring. The chain ends with a *Do method that actually sends the request.

Headers

Per-request (returns a *Builder):

greq.New("https://api.example.com").
    UserAgent("my-client/1.0").
    BasicAuth("user", "pass").
    SetHeader("X-Request-ID", "abc-123").
    SetHeaderMap(map[string]string{
        "X-Trace-Id": "t-1",
        "X-Tenant":   "acme",
    }).
    GetDo("/items")

Defaults applied to every request on a *Client:

client := greq.New("https://api.example.com").
    DefaultUserAgent("my-client/1.0").
    DefaultHeader("X-Tenant", "acme")
Content type and body
// JSON
greq.New("https://api.example.com").
    JSONType().
    PostDo("/items", map[string]any{"name": "widget"})

// Form
greq.New("https://api.example.com").
    FormType().
    PostDo("/login", map[string]string{"user": "x", "pass": "y"})

// Raw bytes / reader / string (BytesBody installs a body Provider;
// pass nil as data so PostDo doesn't override it)
greq.New("https://api.example.com").
    WithContentType("application/octet-stream").
    BytesBody([]byte{0x01, 0x02}).
    PostDo("/upload-binary", nil)

Built-in content-type helpers: JSONType(), FormType(), XMLType(), MultipartType(), WithContentType(value).

Query parameters
greq.New("https://api.example.com").
    QueryParams(map[string]string{"page": "1", "size": "20"}).
    GetDo("/items")
Per-request options

For per-call configuration without re-chaining, use OptionFn helpers:

greq.GetDo("https://api.example.com/items",
    greq.WithHeader("X-Trace", "abc"),
    greq.WithTimeout(2000),          // 2s, in ms
    greq.WithMaxRetries(3),
)

Available: WithMethod, WithContentType, WithUserAgent, WithHeader, WithBody, WithData, WithTimeout, WithRetry, WithMaxRetries, WithRetryDelay, WithRetryChecker.

Handling responses

resp, err := greq.New("https://api.example.com").GetDo("/items")
if err != nil { return err }

if resp.IsFail() {                  // 4xx/5xx
    return fmt.Errorf("status %d", resp.StatusCode)
}

// Decode JSON into a struct (uses Client.RespDecoder, JSON by default)
var items []Item
if err := resp.Decode(&items); err != nil {
    return err
}

Response helpers:

  • Status: IsOK, IsSuccessful, IsFail, IsEmptyBody
  • Content type: ContentType, IsContentType(prefix), IsJSONType
  • Body: Decode(ptr), BodyString / BodyStringE, BodyBuffer / BodyBufferE
  • File output: SaveFile(path) (refuses non-2xx), SaveBody(path) (writes regardless)
  • Inspection: String() (full HTTP response as text), HeaderString()
  • Lifecycle: CloseBody, QuietCloseBody

The plain BodyBuffer / BodyString panic on a read error; prefer the …E variants if you handle untrusted endpoints or care about resilience under load.

Middleware

mid := greq.MiddleFunc(func(r *http.Request, next greq.HandleFunc) (*greq.Response, error) {
    start := time.Now()
    resp, err := next(r)
    log.Printf("%s %s -> %v in %s", r.Method, r.URL, err, time.Since(start))
    return resp, err
})

greq.New("https://api.example.com").
    Middleware(mid).
    GetDo("/items")

Middlewares execute in declaration order on the request and unwind in reverse on the response.

Retry

By default, no retries. Enable per-client:

client := greq.New("https://api.example.com").
    WithMaxRetries(3).
    WithRetryDelay(200) // ms between attempts

DefaultRetryChecker retries on network errors, HTTP 5xx, and HTTP 429.

Per-request override:

greq.GetDo("https://api.example.com/flaky",
    greq.WithRetry(5, 100, greq.DefaultRetryChecker),
)

Custom retry policy:

onlyOn503 := func(resp *greq.Response, err error, attempt int) bool {
    return resp != nil && resp.StatusCode == 503
}
greq.New("https://api.example.com").
    WithRetryConfig(3, 200, onlyOn503).
    GetDo("/path")

Upload / Download

// Download to file (refuses non-2xx; use Response.SaveBody for unconditional)
client := greq.New("https://example.com")
n, err := client.Download("/file.zip", "./out.zip")

// Single file
resp, err := client.UploadFile("/upload", "file", "./photo.jpg")

// Multiple files
resp, err = client.UploadFiles("/upload", map[string]string{
    "image1": "./a.jpg",
    "image2": "./b.jpg",
})

// Files + extra form fields
resp, err = client.UploadWithData("/upload",
    map[string]string{"avatar": "./me.png"},
    map[string]string{"user_id": "42"},
)

See docs/upload-download.md for resumable download, progress callbacks, and advanced multipart options.

Batch requests (ext/batch)

Concurrent fan-out with a worker pool:

import "github.com/gookit/greq/ext/batch"

// Wait for all
results := batch.GetAll([]string{
    "https://api.example.com/a",
    "https://api.example.com/b",
    "https://api.example.com/c",
})
for id, r := range results {
    fmt.Println(id, r.Response.StatusCode, r.Duration)
}

// Return the first success (cancels the rest)
winner := batch.GetAny([]string{
    "https://mirror1.example.com/file",
    "https://mirror2.example.com/file",
})

// Mixed methods, custom processor
bp := batch.NewProcessor(
    batch.WithMaxConcurrency(8),
    batch.WithBatchTimeout(10 * time.Second),
)
bp.AddGet("list", "https://api.example.com/list")
bp.AddPost("submit", "https://api.example.com/submit", map[string]string{"k": "v"})
all := bp.ExecuteAll()

If every request fails, ExecuteAny returns nil promptly rather than waiting for the batch timeout.

.http file format

greq can parse and send the IDE .http request format directly:

raw := `POST https://api.example.com/items?tenant=${tenant}
Content-Type: application/json
Authorization: Bearer ${token}

{"name": "widget"}`

resp, err := greq.New().SendRaw(raw, map[string]string{
    "tenant": "acme",
    "token":  os.Getenv("API_TOKEN"),
})

Variables use the ${name} syntax. Unresolved variables fall back to process environment variables, then are left as the literal name. See ext/httpfile for direct access to the parser.

Custom Doer / testing

greq.Client.Doer(...) swaps the underlying transport — useful for mocking in tests:

import "github.com/gookit/goutil/netutil/httpreq"

client := greq.New("https://api.example.com").
    Doer(httpreq.DoerFunc(func(req *http.Request) (*http.Response, error) {
        // return a recorded response without hitting the network
        return httptest.NewRecorder().Result(), nil
    }))

The same BeforeSend / AfterSend hooks are available on Client for request signing, logging, and metric collection.

Cloning a client

Sub() returns a shallow copy with its own headers map, suitable for per-call customization without affecting the parent:

base := greq.New("https://api.example.com").
    DefaultUserAgent("svc/1.0").
    WithMaxRetries(3)

sub := base.Sub().DefaultHeader("X-Trace", "abc-123")
sub.GetDo("/items")   // inherits retries, user-agent; adds trace header

CLI tools

greq — HTTP client
go install github.com/gookit/greq/cmd/greq@latest

greq https://httpbin.org/get
greq -J name=inhere -J age=18 https://httpbin.org/post
greq --json-type -d @body.json https://httpbin.org/post
greq --json-type -d '{"name":"inhere"}' https://httpbin.org/post
greq -U file=./photo.jpg -F name=inhere https://httpbin.org/post
greq -X PUT -U file=./photo.jpg https://httpbin.org/put
greq -r req.http                          # send an .http file
greq -r req.http -V token=$API_TOKEN      # with variables
greq -O https://example.com/file.zip      # treat URL as download

Full flags: greq -h.

gbench — benchmark tool
go install github.com/gookit/greq/cmd/gbench@latest

gbench -n 1000 -c 10 https://example.com
gbench -z 30s  -c 20 https://example.com           # run for 30 seconds
gbench -n 1000 -c 10 -m POST -d '{"k":"v"}' https://example.com/api
gbench -n 100  -c 5 -o results.txt https://example.com

gbench shows a live progress bar and honors Ctrl+C by stopping gracefully and printing partial results.

See also

Documentation

Overview

Package greq is a simple http client request builder, support batch requests.

Index

Constants

View Source
const (
	HeaderUAgent = "User-Agent"
	HeaderAuth   = "Authorization"

	AgentCURL = "CURL/7.64.1 greq/1.0.2"
)

Variables

View Source
var DefaultDoer = http.DefaultClient

DefaultDoer for request.

Functions

func DefaultRetryChecker added in v0.5.0

func DefaultRetryChecker(resp *Response, err error, attempt int) bool

DefaultRetryChecker is the default retry condition checker It retries on: - Network errors (err != nil) - 5xx server errors - 429 Too Many Requests

func NewTransport added in v0.5.0

func NewTransport(onCreate func(ht *http.Transport)) *http.Transport

NewTransport create new http transport

Types

type AfterSendFn added in v0.3.0

type AfterSendFn func(resp *Response, err error)

AfterSendFn callback func

type BodyProvider

type BodyProvider interface {
	// ContentType returns the Content-Type of the body.
	ContentType() string
	// Body returns the io.Reader body.
	Body() (io.Reader, error)
}

BodyProvider provides Body content for http.Request attachment.

Concrete implementations live in internal/bodyprovider; users may also implement this interface themselves and pass it via Builder.BodyProvider.

type Builder added in v0.3.0

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

Builder is an http request builder.

func BuilderWithClient added in v0.3.0

func BuilderWithClient(c *Client, optFns ...OptionFn) *Builder

BuilderWithClient create a new builder with client

func NewBuilder added in v0.3.0

func NewBuilder(fns ...OptionFn) *Builder

NewBuilder for request

func (*Builder) AddHeader added in v0.3.0

func (b *Builder) AddHeader(key, value string) *Builder

AddHeader adds the key, value pair in HeaderM, appending values for existing keys to the key's values. Header keys are canonicalized.

func (*Builder) AddHeaderMap added in v0.3.0

func (b *Builder) AddHeaderMap(headers map[string]string) *Builder

AddHeaderMap sets all the http.Header values, appending values for existing keys to the key's values.

func (*Builder) AddHeaders added in v0.3.0

func (b *Builder) AddHeaders(headers http.Header) *Builder

AddHeaders adds all the http.Header values, appending values for existing keys to the key's values. Header keys are canonicalized.

func (*Builder) AddQuery added in v0.3.0

func (b *Builder) AddQuery(key string, value any) *Builder

AddQuery appends new k-v param to the Query string.

func (*Builder) AnyBody added in v0.3.0

func (b *Builder) AnyBody(body any) *Builder

AnyBody with custom any type body

func (*Builder) BasicAuth added in v0.3.0

func (b *Builder) BasicAuth(username, password string) *Builder

BasicAuth sets the Authorization header to use HTTP Basic Authentication with the provided username and password.

With HTTP Basic Authentication the provided username and password are not encrypted.

func (*Builder) BodyProvider added in v0.3.0

func (b *Builder) BodyProvider(bp BodyProvider) *Builder

BodyProvider with custom body provider

func (*Builder) BodyReader added in v0.3.0

func (b *Builder) BodyReader(r io.Reader) *Builder

BodyReader with custom io reader body

func (*Builder) Build added in v0.3.0

func (b *Builder) Build(method, pathURL string) (*http.Request, error)

Build request

func (*Builder) BytesBody added in v0.3.0

func (b *Builder) BytesBody(bs []byte) *Builder

BytesBody with custom string body

func (*Builder) Delete added in v0.3.0

func (b *Builder) Delete(pathURL string, optFns ...OptionFn) *Builder

Delete sets the method to DELETE and sets the given pathURL

func (*Builder) DeleteDo added in v0.3.0

func (b *Builder) DeleteDo(pathURL string, optFns ...OptionFn) (*Response, error)

DeleteDo sets the method to DELETE and sets the given pathURL, then send request and return response.

func (*Builder) Do added in v0.3.0

func (b *Builder) Do(optFns ...OptionFn) (*Response, error)

Do send request and return response.

func (*Builder) FileContentsBody added in v0.3.0

func (b *Builder) FileContentsBody(filePath string) *Builder

FileContentsBody read file contents as body

func (*Builder) FormBody added in v0.3.0

func (b *Builder) FormBody(formData any) *Builder

FormBody with form data body

func (*Builder) FormType added in v0.3.0

func (b *Builder) FormType() *Builder

FormType with from Content-Type header

func (*Builder) Get added in v0.3.0

func (b *Builder) Get(pathURL string, optFns ...OptionFn) *Builder

Get sets the method to GET and sets the given pathURL

func (*Builder) GetDo added in v0.3.0

func (b *Builder) GetDo(pathURL string, optFns ...OptionFn) (*Response, error)

GetDo sets the method to GET and sets the given pathURL, then send request and return response.

func (*Builder) JSONBody added in v0.3.0

func (b *Builder) JSONBody(jsonData any) *Builder

JSONBody with JSON data body

func (*Builder) JSONType added in v0.3.0

func (b *Builder) JSONType() *Builder

JSONType with json Content-Type header

func (*Builder) Multipart added in v0.3.0

func (b *Builder) Multipart(key, value string) *Builder

Multipart with custom multipart body

func (*Builder) MultipartType added in v0.3.0

func (b *Builder) MultipartType() *Builder

MultipartType with multipart/form-data Content-Type header

func (*Builder) Patch added in v0.3.0

func (b *Builder) Patch(pathURL string, data any, optFns ...OptionFn) *Builder

Patch sets the method to PATCH and sets the given pathURL

func (*Builder) PatchDo added in v0.3.0

func (b *Builder) PatchDo(pathURL string, data any, optFns ...OptionFn) (*Response, error)

PatchDo sets the method to PATCH and sets the given pathURL, then send request and return response.

func (*Builder) PathURL added in v0.3.0

func (b *Builder) PathURL(pathURL string) *Builder

PathURL set path URL for current request

func (*Builder) Post added in v0.3.0

func (b *Builder) Post(pathURL string, data any, optFns ...OptionFn) *Builder

Post sets the method to POST and sets the given pathURL

func (*Builder) PostDo added in v0.3.0

func (b *Builder) PostDo(pathURL string, data any, optFns ...OptionFn) (*Response, error)

PostDo sets the method to POST and sets the given pathURL, then send request and return http response.

func (*Builder) Put added in v0.3.0

func (b *Builder) Put(pathURL string, data any, optFns ...OptionFn) *Builder

Put sets the method to PUT and sets the given pathURL

func (*Builder) PutDo added in v0.3.0

func (b *Builder) PutDo(pathURL string, data any, optFns ...OptionFn) (*Response, error)

PutDo sets the method to PUT and sets the given pathURL, then send request and return response.

func (*Builder) QueryParams added in v0.3.0

func (b *Builder) QueryParams(ps any) *Builder

QueryParams appends url.Values/map[string]string to the Query string. The value will be encoded as url Query parameters on send requests (see Send()).

func (*Builder) QueryValues added in v0.3.0

func (b *Builder) QueryValues(values gourl.Values) *Builder

QueryValues appends url.Values to the Query string. The value will be encoded as url Query parameters on new requests (see Send()).

func (*Builder) RemoveHeaders added in v0.5.0

func (b *Builder) RemoveHeaders(keys ...string) *Builder

RemoveHeaders removes the keys from HeaderM.

func (*Builder) Send added in v0.3.0

func (b *Builder) Send(method, url string, optFns ...OptionFn) (*Response, error)

Send request and return response, alias of Do()

func (*Builder) SetHeader added in v0.3.0

func (b *Builder) SetHeader(key, value string) *Builder

SetHeader sets the key, value pair in HeaderM, replacing existing values associated with key. Header keys are canonicalized.

func (*Builder) SetHeaderMap added in v0.3.0

func (b *Builder) SetHeaderMap(headers map[string]string) *Builder

SetHeaderMap sets all the http.Header values, replacing values for existing keys to the key's values.

func (*Builder) SetHeaders added in v0.3.0

func (b *Builder) SetHeaders(headers http.Header) *Builder

SetHeaders sets all the http.Header values, replacing values for existing keys to the key's values. Header keys are canonicalized.

func (*Builder) String added in v0.3.0

func (b *Builder) String() string

String request to string.

func (*Builder) StringBody added in v0.3.0

func (b *Builder) StringBody(s string) *Builder

StringBody with custom string body

func (*Builder) UserAgent added in v0.3.0

func (b *Builder) UserAgent(ua string) *Builder

UserAgent set User-Agent header

func (*Builder) UserAuth added in v0.3.0

func (b *Builder) UserAuth(value string) *Builder

UserAuth with user auth header value.

func (*Builder) WithBody added in v0.3.0

func (b *Builder) WithBody(body any) *Builder

WithBody with custom any type body

func (*Builder) WithClient added in v0.3.0

func (b *Builder) WithClient(c *Client) *Builder

WithClient set cli to builder

func (*Builder) WithContentType added in v0.3.0

func (b *Builder) WithContentType(value string) *Builder

WithContentType with custom ContentType header

func (*Builder) WithCookieString added in v0.3.0

func (b *Builder) WithCookieString(value string) *Builder

WithCookieString set cookie header value.

Usage:

h.NewOpt().
	WithCookieString("name=inhere;age=30").
	Do("/some/api", "GET")

func (*Builder) WithCookies added in v0.3.0

func (b *Builder) WithCookies(hcs ...*http.Cookie) *Builder

WithCookies to request

func (*Builder) WithMethod added in v0.3.0

func (b *Builder) WithMethod(method string) *Builder

WithMethod set request method name.

func (*Builder) WithOptionFn added in v0.3.0

func (b *Builder) WithOptionFn(fns ...OptionFn) *Builder

WithOptionFn set option fns to builder

func (*Builder) WithOptionFns added in v0.3.0

func (b *Builder) WithOptionFns(fns []OptionFn) *Builder

WithOptionFns set option fns to builder

func (*Builder) WithQuerySMap added in v0.3.0

func (b *Builder) WithQuerySMap(smp map[string]string) *Builder

WithQuerySMap appends map[string]string to the Query string.

func (*Builder) WithType added in v0.3.0

func (b *Builder) WithType(value string) *Builder

WithType with custom ContentType header

func (*Builder) XMLType added in v0.3.0

func (b *Builder) XMLType() *Builder

XMLType with xml Content-Type header

type Client added in v0.3.0

type Client struct {

	// Method default http method. default is GET
	Method string
	// Header default http header. default is nil
	Header http.Header
	// defalut content type
	ContentType string
	// BaseURL default base URL. default is ""
	BaseURL string
	// Timeout default timeout(ms) for each request. default 10s
	//
	//  - 0: not limit
	Timeout int
	// RespDecoder response data decoder.
	//  - use for create Response instance. default is JSON decoder
	RespDecoder RespDecoder

	// ReqVars template vars for request: URL, Header, Query, Body
	//
	// eg: http://example.com/${name}
	ReqVars map[string]string
	// BeforeSend callback on each request, can return error to deny request.
	BeforeSend func(r *http.Request) error
	// AfterSend callback on each request, can use for record request and response
	AfterSend AfterSendFn

	// MaxRetries max retry times. default is 0 (not retry)
	MaxRetries int
	// RetryDelay retry delay time (ms). default is 0 (no delay)
	RetryDelay int
	// RetryChecker retry condition checker. default is nil (not retry)
	RetryChecker RetryChecker
	// contains filtered or unexported fields
}

Client is an HTTP Request builder and sender.

func BaseURL

func BaseURL(baseURL string) *Client

BaseURL set base URL for request

func New

func New(baseURL ...string) *Client

New create a new http request client.

func NewClient added in v0.5.0

func NewClient(baseURL ...string) *Client

NewClient create a new http request client. alias of New()

func Reset

func Reset() *Client

Reset std default settings

func Std

func Std() *Client

Std instance

func (*Client) AnyBody added in v0.3.0

func (h *Client) AnyBody(body any) *Builder

AnyBody with custom any type body

func (*Client) BasicAuth added in v0.3.0

func (h *Client) BasicAuth(username, password string) *Builder

BasicAuth sets the Authorization header to use HTTP Basic Authentication with the provided username and password.

With HTTP Basic Authentication the provided username and password are not encrypted.

func (*Client) Body added in v0.3.0

func (h *Client) Body(body any) *Builder

Body with custom any type body

func (*Client) BodyProvider added in v0.3.0

func (h *Client) BodyProvider(bp BodyProvider) *Builder

BodyProvider with custom body provider

func (*Client) BodyReader added in v0.3.0

func (h *Client) BodyReader(r io.Reader) *Builder

BodyReader with custom io reader body

func (*Client) Builder added in v0.3.0

func (h *Client) Builder(optFns ...OptionFn) *Builder

Builder create a new builder with current client.

func (*Client) Client added in v0.3.0

func (h *Client) Client(doer httpreq.Doer) *Client

Client custom set http request doer

func (*Client) Config added in v0.3.0

func (h *Client) Config(fn func(h *Client)) *Client

Config custom config for client.

Usage:

h.Config(func(h *Client) {
	h.Method = http.MethodPost
})

func (*Client) ConfigDoer added in v0.5.0

func (h *Client) ConfigDoer(fn func(doer httpreq.Doer)) *Client

ConfigDoer custom config http request doer

func (*Client) ConfigHClient added in v0.3.0

func (h *Client) ConfigHClient(fn func(hClient *http.Client)) *Client

ConfigHClient custom config http client.

Usage:

h.ConfigHClient(func(hClient *http.Client) {
	hClient.Timeout = 30 * time.Second
})

func (*Client) DefaultBasicAuth added in v0.3.0

func (h *Client) DefaultBasicAuth(username, password string) *Client

DefaultBasicAuth sets the Authorization header to use HTTP Basic Authentication with the provided username and password. With HTTP Basic Authentication the provided username and password are not encrypted.

func (*Client) DefaultContentType added in v0.3.0

func (h *Client) DefaultContentType(value string) *Client

DefaultContentType set default ContentType header, it will be used for all requests.

Usage:

// json type
h.DefaultContentType(httpctype.JSON)
// form type
h.DefaultContentType(httpctype.Form)

func (*Client) DefaultHeader added in v0.3.0

func (h *Client) DefaultHeader(key, value string) *Client

DefaultHeader sets the http.Header value, it will be used for all requests.

func (*Client) DefaultHeaders added in v0.3.0

func (h *Client) DefaultHeaders(headers http.Header) *Client

DefaultHeaders sets all the http.Header values, it will be used for all requests.

func (*Client) DefaultMethod added in v0.3.0

func (h *Client) DefaultMethod(method string) *Client

DefaultMethod set default method name. it will be used when the Get()/Post() method is empty.

func (*Client) DefaultTimeout added in v0.5.0

func (h *Client) DefaultTimeout(timeoutMs int) *Client

DefaultTimeout set default timeout in milliseconds for requests. default is 0 (infinite)

func (*Client) DefaultUserAgent added in v0.3.0

func (h *Client) DefaultUserAgent(value string) *Client

DefaultUserAgent with User-Agent header setting for all requests.

func (*Client) DefaultUserAuth added in v0.3.0

func (h *Client) DefaultUserAuth(value string) *Client

DefaultUserAuth with user auth header value for all requests.

func (*Client) Delete added in v0.3.0

func (h *Client) Delete(pathURL string) *Builder

Delete sets the method to DELETE and sets the given pathURL

func (*Client) DeleteDo added in v0.3.0

func (h *Client) DeleteDo(pathURL string, optFns ...OptionFn) (*Response, error)

DeleteDo sets the method to DELETE and sets the given pathURL, then send request and return http response.

func (*Client) Do added in v0.3.0

func (h *Client) Do(method, url string, optFns ...OptionFn) (*Response, error)

Do send request and return response

func (*Client) DoWithOption added in v0.3.0

func (h *Client) DoWithOption(method, url string, optFns ...OptionFn) (*Response, error)

DoWithOption request with options, then return response

func (*Client) Doer added in v0.3.0

func (h *Client) Doer(doer httpreq.Doer) *Client

Doer custom set http request doer. If a nil cli is given, the DefaultDoer will be used.

func (*Client) Download added in v0.5.0

func (h *Client) Download(url, savePath string, optFns ...OptionFn) (int, error)

Download remote file from url and save to savePath.

func (*Client) FormType added in v0.3.0

func (h *Client) FormType() *Builder

FormType with from Content-Type header

func (*Client) Get added in v0.3.0

func (h *Client) Get(pathURL string) *Builder

Get sets the method to GET and sets the given pathURL

func (*Client) GetDo added in v0.3.0

func (h *Client) GetDo(pathURL string, optFns ...OptionFn) (*Response, error)

GetDo sets the method to GET and sets the given pathURL, then send request and return response.

func (*Client) Head added in v0.3.0

func (h *Client) Head(pathURL string) *Builder

Head sets the method to HEAD and request the pathURL, then send request and return response.

func (*Client) HeadDo added in v0.3.0

func (h *Client) HeadDo(pathURL string, optFns ...OptionFn) (*Response, error)

HeadDo sets the method to HEAD and request the pathURL, then send request and return response.

func (*Client) HttpClient added in v0.3.0

func (h *Client) HttpClient(hClient *http.Client) *Client

HttpClient custom set http cli as request doer

func (*Client) JSONType added in v0.3.0

func (h *Client) JSONType() *Builder

JSONType with json Content-Type header

func (*Client) Middleware added in v0.3.0

func (h *Client) Middleware(middles ...Middleware) *Client

Middleware add one or multi middlewares

func (*Client) Middlewares added in v0.3.0

func (h *Client) Middlewares(middles ...Middleware) *Client

Middlewares add one or multi middlewares.

Not safe to call concurrently with in-flight requests — call during setup before requests are dispatched.

func (*Client) MustSend added in v0.3.0

func (h *Client) MustSend(method, url string, optFns ...OptionFn) *Response

MustSend send request and return response, will panic on error

func (*Client) NewRequest added in v0.3.0

func (h *Client) NewRequest(method, url string, optFns ...OptionFn) (*http.Request, error)

NewRequest build new request

func (*Client) NewRequestWithOptions added in v0.3.0

func (h *Client) NewRequestWithOptions(url string, opt *Options) (*http.Request, error)

NewRequestWithOptions build new request with Options

func (*Client) OnBeforeSend added in v0.3.0

func (h *Client) OnBeforeSend(fn func(r *http.Request) error) *Client

OnBeforeSend for cli

func (*Client) Patch added in v0.3.0

func (h *Client) Patch(pathURL string) *Builder

Patch sets the method to PATCH and sets the given pathURL

func (*Client) PatchDo added in v0.3.0

func (h *Client) PatchDo(pathURL string, optFns ...OptionFn) (*Response, error)

PatchDo sets the method to PATCH and sets the given pathURL, then send request and return http response.

func (*Client) Post added in v0.3.0

func (h *Client) Post(pathURL string) *Builder

Post sets the method to POST and sets the given pathURL

func (*Client) PostDo added in v0.3.0

func (h *Client) PostDo(pathURL string, optFns ...OptionFn) (*Response, error)

PostDo sets the method to POST and sets the given pathURL, then send request and return http response.

func (*Client) Put added in v0.3.0

func (h *Client) Put(pathURL string) *Builder

Put sets the method to PUT and sets the given pathURL

func (*Client) PutDo added in v0.3.0

func (h *Client) PutDo(pathURL string, optFns ...OptionFn) (*Response, error)

PutDo sets the method to PUT and sets the given pathURL, then send request and return http response.

func (*Client) QueryParams added in v0.3.0

func (h *Client) QueryParams(ps any) *Builder

QueryParams appends url.Values/map[string]string to the Query string. The value will be encoded as url Query parameters on send requests (see Send()).

func (*Client) Send added in v0.3.0

func (h *Client) Send(method, url string, optFns ...OptionFn) (*Response, error)

Send request and return response, alias of Do()

func (*Client) SendRaw added in v0.3.0

func (h *Client) SendRaw(raw string, varMp map[string]string) (*Response, error)

SendRaw http request text. like IDE .http file contents

Format:

POST https://example.com/path?name=inhere
Content-Type: application/json
Accept: */*

<content>

func (*Client) SendRequest added in v0.3.0

func (h *Client) SendRequest(req *http.Request) (*Response, error)

SendRequest sends a pre-built request using the Client-level retry config.

func (*Client) SendWithOpt added in v0.3.0

func (h *Client) SendWithOpt(pathURL string, opt *Options) (*Response, error)

SendWithOpt send request with option, then return response

func (*Client) SendWithOption added in v0.3.0

func (h *Client) SendWithOption(method, url string, optFns ...OptionFn) (*Response, error)

SendWithOption request with options, then return response

func (*Client) SetMaxIdleConns added in v0.5.0

func (h *Client) SetMaxIdleConns(maxIdleConns, maxIdleConnsPerHost int) *Client

SetMaxIdleConns Set the maximum number of idle connections.

func (*Client) String added in v0.3.0

func (h *Client) String() string

String request to string.

func (*Client) Sub added in v0.3.0

func (h *Client) Sub() *Client

Sub create an instance from current. will inherit all options

func (*Client) UploadFile added in v0.5.0

func (h *Client) UploadFile(pathURL, fieldName, filePath string, optFns ...OptionFn) (*Response, error)

UploadFile uploads a single file to the given URL.

func (*Client) UploadFiles added in v0.5.0

func (h *Client) UploadFiles(pathURL string, files map[string]string, optFns ...OptionFn) (*Response, error)

UploadFiles uploads multiple files to the given URL.

func (*Client) UploadWithData added in v0.5.0

func (h *Client) UploadWithData(pathURL string, files map[string]string, fields map[string]string, optFns ...OptionFn) (*Response, error)

UploadWithData uploads files with additional form fields.

func (*Client) Use added in v0.3.0

func (h *Client) Use(middles ...Middleware) *Client

Use one or multi middlewares

func (*Client) UserAgent added in v0.3.0

func (h *Client) UserAgent(value string) *Builder

UserAgent with User-Agent header setting for all requests.

func (*Client) UserAuth added in v0.3.0

func (h *Client) UserAuth(value string) *Builder

UserAuth with user auth header value for all requests.

func (*Client) Uses added in v0.3.0

func (h *Client) Uses(middles ...Middleware) *Client

Uses one or multi middlewares

func (*Client) WithBaseURL added in v0.5.0

func (h *Client) WithBaseURL(baseURL string) *Client

WithBaseURL set default base URL for all request

func (*Client) WithContentType added in v0.3.0

func (h *Client) WithContentType(value string) *Builder

WithContentType with custom Content-Type header

func (*Client) WithMaxRetries added in v0.5.0

func (h *Client) WithMaxRetries(maxRetries int) *Client

WithMaxRetries set max retry times

func (*Client) WithRespDecoder added in v0.3.0

func (h *Client) WithRespDecoder(respDecoder RespDecoder) *Client

WithRespDecoder for cli

func (*Client) WithRetryChecker added in v0.5.0

func (h *Client) WithRetryChecker(checker RetryChecker) *Client

WithRetryChecker set custom retry checker function

func (*Client) WithRetryConfig added in v0.5.0

func (h *Client) WithRetryConfig(maxRetries, retryDelay int, checker RetryChecker) *Client

WithRetryConfig set retry configuration

func (*Client) WithRetryDelay added in v0.5.0

func (h *Client) WithRetryDelay(retryDelay int) *Client

WithRetryDelay set retry delay time in milliseconds

type HandleFunc

type HandleFunc func(r *http.Request) (*Response, error)

HandleFunc for the Middleware

type MiddleFunc

type MiddleFunc func(r *http.Request, next HandleFunc) (*Response, error)

MiddleFunc implements the Middleware interface

func (MiddleFunc) Handle

func (mf MiddleFunc) Handle(r *http.Request, next HandleFunc) (*Response, error)

Handle request

type Middleware

type Middleware interface {
	Handle(r *http.Request, next HandleFunc) (*Response, error)
}

Middleware interface for cli request.

type OptionFn added in v0.3.0

type OptionFn func(opt *Options)

OptionFn for config request options

func WithBody added in v0.5.0

func WithBody(body any) OptionFn

WithBody set body data

func WithContentType added in v0.3.0

func WithContentType(contentType string) OptionFn

WithContentType set content-type

func WithData added in v0.5.0

func WithData(data any) OptionFn

WithData set data for request

func WithHeader added in v0.5.0

func WithHeader(key, value string) OptionFn

WithHeader set header

func WithMaxRetries added in v0.5.0

func WithMaxRetries(maxRetries int) OptionFn

WithMaxRetries set max retry times for the request

func WithMethod added in v0.3.0

func WithMethod(method string) OptionFn

WithMethod set method

func WithRetry added in v0.5.0

func WithRetry(maxRetries, retryDelay int, checker RetryChecker) OptionFn

WithRetry set retry configuration for the request

func WithRetryChecker added in v0.5.0

func WithRetryChecker(checker RetryChecker) OptionFn

WithRetryChecker set custom retry checker function for the request

func WithRetryDelay added in v0.5.0

func WithRetryDelay(retryDelay int) OptionFn

WithRetryDelay set retry delay time in milliseconds for the request

func WithTimeout added in v0.5.0

func WithTimeout(timeoutMs int) OptionFn

WithTimeout set timeout (ms)

func WithUserAgent added in v0.3.0

func WithUserAgent(userAgent string) OptionFn

WithUserAgent set user-agent header

type Options added in v0.3.0

type Options struct {

	// Method for request
	Method string
	// ContentType header
	ContentType string
	// Headers for request
	Header http.Header
	// HeaderM map string data.
	HeaderM map[string]string

	// Query params data.
	Query  gourl.Values
	QueryM map[string]any

	// Data for request. Will be encoded to query string or request body.
	//
	// type allow: string, []byte, io.Reader, io.ReadCloser, url.Values, map[string]string
	Data any
	// Body data for request, only for POST, PUT, PATCH
	//
	// type allow: string, []byte, io.Reader, io.ReadCloser, url.Values, map[string]string
	Body any
	// Provider body data provider, can with custom content-type.
	//
	// Do NOT assign a typed nil pointer here (e.g. var p *MyProvider; opt.Provider = p):
	// the interface compares non-nil, the request build path calls p.Body(), and you get
	// a panic. Leave the field as its zero value if you have no provider.
	Provider BodyProvider

	// EncodeJSON req body
	EncodeJSON bool
	// Timeout unit: ms
	Timeout int
	// TCancelFn will auto set it on Timeout > 0
	TCancelFn context.CancelFunc
	// Context for request
	Context context.Context
	// Logger for request
	Logger httpreq.ReqLogger

	// Retry configuration
	MaxRetries   int
	RetryDelay   int
	RetryChecker RetryChecker
	// contains filtered or unexported fields
}

Options for one request build

func NewOpt added in v0.3.0

func NewOpt(fns ...OptionFn) *Options

NewOpt for request

func NewOpt2 added in v0.3.0

func NewOpt2(fns []OptionFn, method string) *Options

NewOpt2 for request

type RequestCreator

type RequestCreator interface {
	NewRequest(method, target string, body io.Reader) *http.Request
}

RequestCreator interface

type RequestCreatorFunc

type RequestCreatorFunc func(method, target string, body io.Reader) *http.Request

RequestCreatorFunc func

type RespDecoder

type RespDecoder interface {
	// Decode decodes the response into the value pointed to by ptr.
	Decode(resp *http.Response, ptr any) error
}

RespDecoder decodes http responses into struct values.

type Response

type Response struct {
	// raw http.Response
	*http.Response
	// CostTime for a request-response. unit: ms
	CostTime int64
	// contains filtered or unexported fields
}

Response is a http.Response wrapper, add some useful methods.

func ConnectDo

func ConnectDo(pathURL string, optFns ...OptionFn) (*Response, error)

ConnectDo sets the method to CONNECT and sets the given pathURL, then send request and return http response.

func DeleteDo

func DeleteDo(pathURL string, optFns ...OptionFn) (*Response, error)

DeleteDo sets the method to DELETE and sets the given pathURL, then send request and return http response.

func GetDo

func GetDo(pathURL string, optFns ...OptionFn) (*Response, error)

GetDo sets the method to GET and sets the given pathURL, then send request and return response.

func HeadDo added in v0.3.0

func HeadDo(pathURL string, optFns ...OptionFn) (*Response, error)

HeadDo sets the method to HEAD and request the pathURL, then send request and return response.

func Must added in v0.3.0

func Must(w *Response, err error) *Response

Must return response, if error will panic

func MustDo added in v0.3.0

func MustDo(method, pathURL string, optFns ...OptionFn) *Response

MustDo sets the method to POST and sets the given pathURL, then send request and return http response.

func NewResponse added in v0.5.0

func NewResponse(resp *http.Response, decoder RespDecoder) *Response

NewResponse create a new Response instance

func OptionsDo

func OptionsDo(pathURL string, optFns ...OptionFn) (*Response, error)

OptionsDo sets the method to OPTIONS and request the pathURL, then send request and return response.

func PatchDo

func PatchDo(pathURL string, data any, optFns ...OptionFn) (*Response, error)

PatchDo sets the method to PATCH and sets the given pathURL, then send request and return http response.

func PostDo

func PostDo(pathURL string, data any, optFns ...OptionFn) (*Response, error)

PostDo sets the method to POST and sets the given pathURL, then send request and return http response.

func PutDo

func PutDo(pathURL string, data any, optFns ...OptionFn) (*Response, error)

PutDo sets the method to PUT and sets the given pathURL, then send request and return http response.

func SendDo added in v0.3.0

func SendDo(method, pathURL string, optFns ...OptionFn) (*Response, error)

SendDo sets the method to POST and sets the given pathURL, then send request and return http response.

func TraceDo

func TraceDo(pathURL string, optFns ...OptionFn) (*Response, error)

TraceDo sets the method to TRACE and sets the given pathURL, then send request and return http response.

func (*Response) BodyBuffer

func (r *Response) BodyBuffer() *bytes.Buffer

BodyBuffer reads body to buffer. Panics on read error — kept for backward compatibility. Prefer BodyBufferE for new code so a transient network error during read doesn't crash the program.

NOTICE: closes resp body.

func (*Response) BodyBufferE added in v0.6.0

func (r *Response) BodyBufferE() (*bytes.Buffer, error)

BodyBufferE reads body to buffer and returns any read error.

NOTICE: closes resp body.

func (*Response) BodyString

func (r *Response) BodyString() string

BodyString reads response body as string. Panics on read error; prefer BodyStringE for new code.

func (*Response) BodyStringE added in v0.6.0

func (r *Response) BodyStringE() (string, error)

BodyStringE reads response body as string and returns any read error.

func (*Response) CloseBody

func (r *Response) CloseBody() error

CloseBody close resp body

func (*Response) ContentType

func (r *Response) ContentType() string

ContentType get response content type

func (*Response) Decode

func (r *Response) Decode(ptr any) error

Decode get the raw http.Response

func (*Response) HeaderString

func (r *Response) HeaderString() string

HeaderString convert response headers to string

func (*Response) IsContentType

func (r *Response) IsContentType(prefix string) bool

IsContentType check response content type is equals the given.

Usage:

resp, err := greq.Post("some.host/path")
ok := resp.IsContentType("application/xml")

func (*Response) IsEmptyBody

func (r *Response) IsEmptyBody() bool

IsEmptyBody reports whether the response body is known to be empty. Returns true only when Content-Length is explicitly 0; chunked responses (Content-Length == -1) are NOT treated as empty because their actual size isn't known until the stream is consumed.

func (*Response) IsFail

func (r *Response) IsFail() bool

IsFail check response status code != 200

func (*Response) IsJSONType

func (r *Response) IsJSONType() bool

IsJSONType check response content type is JSON

func (*Response) IsOK

func (r *Response) IsOK() bool

IsOK check response status code is 200

func (*Response) IsSuccessful

func (r *Response) IsSuccessful() bool

IsSuccessful check response status code is in 200 - 300

func (*Response) QuietCloseBody

func (r *Response) QuietCloseBody()

QuietCloseBody close resp body, ignore error

func (*Response) SaveBody added in v0.6.0

func (r *Response) SaveBody(file string) (n int, err error)

SaveBody writes the response body to file unconditionally, regardless of status code. Use this when you intend to capture error pages too.

func (*Response) SaveFile added in v0.3.0

func (r *Response) SaveFile(file string) (n int, err error)

SaveFile writes the response body to file. Returns an error (without writing anything) if the response status is not 2xx — otherwise a 404 HTML page or 500 stack trace would silently get saved as the "file".

Call SaveBody if you really want to save regardless of status.

func (*Response) SetDecoder

func (r *Response) SetDecoder(decoder RespDecoder)

SetDecoder for response

func (*Response) String

func (r *Response) String() string

String convert Response to string

type RetryChecker added in v0.5.0

type RetryChecker func(resp *Response, err error, attempt int) bool

RetryChecker function type for checking if a request should be retried

type XmlDecoder

type XmlDecoder struct{}

XmlDecoder decodes http response body into a XML-tagged struct value.

func (XmlDecoder) Decode

func (d XmlDecoder) Decode(resp *http.Response, ptr any) error

Decode decodes the Response body into the value pointed to by ptr.

Directories

Path Synopsis
cmd
gbench module
greq module
ext
batch
Package batch provides utilities for batch processing HTTP requests
Package batch provides utilities for batch processing HTTP requests
httpfile
Package httpfile provides HTTP request file(.http) parsing utilities.
Package httpfile provides HTTP request file(.http) parsing utilities.
internal
bodyprovider
Package bodyprovider implements the concrete BodyProvider variants used by the greq client (reader, JSON, form, multipart).
Package bodyprovider implements the concrete BodyProvider variants used by the greq client (reader, JSON, form, multipart).

Jump to

Keyboard shortcuts

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