greq

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2026 License: MIT Imports: 22 Imported by: 0

README

Greq

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

中文说明 | English

greq A simple HTTP client request builder and sender, with retry feature.

Features

  • Make HTTP requests, supports GET,POST,PUT,PATCH,DELETE,HEAD
  • Transform request and response data
  • Supports chain configuration request
  • Supports defining and adding middleware
  • Supports defining request body provider and response decoder
  • Supports request retry feature, with default retry checker DefaultRetryChecker
  • Built-In: fom, json request body provider
  • Built-In: xml, json response body decoder
  • Support for directly parsing and sending .http file format requests
  • Supports download and upload file(s)
  • Built-in command tool:
    • cmd/greq Lightweight HTTP request tool similar to curl and supports the IDEA .http file format
    • cmd/gbench Lightweight HTTP request load testing tool similar to ab testing tool

Install

go get github.com/gookit/greq
Install Tools
# HTTP request tool
go install github.com/gookit/greq/cmd/greq@latest
# HTTP request testing
go install github.com/gookit/greq/cmd/gbench@latest

Quick start

package main

import (
	"github.com/gookit/goutil/dump"
	"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)
	}

	ret := make(map[string]any)
	err = resp.Decode(&ret)
	if err != nil {
		panic(err)
	}

	dump.P(ret)
}

Result:

PRINT AT github.com/gookit/greq_test.TestHReq_Send(greq_test.go:73)
map[string]interface {} { #len=4
  "args": map[string]interface {} { #len=0
  },
  "headers": map[string]interface {} { #len=4
    "Host": string("httpbin.org"), #len=11
    "User-Agent": string("custom-client/1.0"), #len=17
    "X-Amzn-Trace-Id": string("Root=1-61e4d41e-06e27ae12ff872a224373ca7"), #len=40
    "Accept-Encoding": string("gzip"), #len=4
  },
  "origin": string("222.210.59.218"), #len=14
  "url": string("https://httpbin.org/post"), #len=24
},

Request headers

greq.New("some.host/api").
	SetHeader("req-id", "a string")

Set multi at once:

greq.New("some.host/api").
	SetHeaders(map[string]string{
		"req-id": "a string",
	})
Set content type
greq.New("some.host/api").
    ContentType("text/html")

Built in JSONType() FromType() XMLType()

greq.New("some.host/api").JSONType()

Use middleware

	buf := &bytes.Buffer{}
	mid0 := greq.MiddleFunc(func(r *http.Request, next greq.HandleFunc) (*greq.Response, error) {
		buf.WriteString("MID0>>")
		w, err := next(r)
		buf.WriteString(">>MID0")
		return w, err
	})

	mid1 := greq.MiddleFunc(func(r *http.Request, next greq.HandleFunc) (*greq.Response, error) {
		buf.WriteString("MID1>>")
		w, err := next(r)
		buf.WriteString(">>MID1")
		return w, err
	})

	mid2 := greq.MiddleFunc(func(r *http.Request, next greq.HandleFunc) (*greq.Response, error) {
		buf.WriteString("MID2>>")
		w, err := next(r)
		buf.WriteString(">>MID2")
		return w, err
	})

	resp, err := greq.New("https://httpbin.org").
		Doer(httpreq.DoerFunc(func(req *http.Request) (*http.Response, error) {
			tw := httptest.NewRecorder()
			buf.WriteString("(CORE)")
			return tw.Result(), nil
		})).
		Middleware(mid0, mid1, mid2).
		GetDo("/get")

    fmt.Println(buf.String())

Output:

MID2>>MID1>>MID0>>(CORE)>>MID0>>MID1>>MID2

More usage

Check response
  • Response.IsOK() bool
  • Response.IsFail() bool
  • Response.IsEmptyBody() bool
  • Response.IsJSONType() bool
  • Response.IsContentType(prefix string) bool
Get response data
  • Response.ContentType() string
  • Response.Decode(ptr any) error
Request to string
    str := greq.New("https://httpbin.org").
		UserAgent("some-client/1.0").
		BasicAuth("inhere", "some string").
		JSONType().
		Body("hi, with body").
		Post("/post").
		String()

	fmt.Println(str)

Output:

POST https://httpbin.org/post/ HTTP/1.1
User-Agent: some-client/1.0
Authorization: Basic aW5oZXJlOnNvbWUgc3RyaW5n
Content-Type: application/json; charset=utf-8

hi, with body
Response to string

greq.Response.String() can convert response to string.

package main

import (
	"fmt"

	"github.com/gookit/goutil/dump"
	"github.com/gookit/greq"
)

func main() {
	resp, err := greq.New("https://httpbin.org").
		UserAgent("custom-client/1.0").
		Send("/get")

	if err != nil {
		panic(err)
	}

	fmt.Print(resp.String())
}

Output:

HTTP/2.0 200 OK
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Date: Tue, 18 Jan 2022 04:52:39 GMT
Content-Type: application/json
Content-Length: 272
Server: gunicorn/19.9.0

{
  "args": {},
  "headers": {
    "Accept-Encoding": "gzip",
    "Host": "httpbin.org",
    "User-Agent": "custom-client/1.0",
    "X-Amzn-Trace-Id": "Root=1-61e64797-3e428a925f7709906a8b7c01"
  },
  "origin": "222.210.59.218",
  "url": "https://httpbin.org/get"
}

Command Tool Usage

greq Tool

cmd/greq Lightweight HTTP request tool similar to curl and supports the IDEA .http file format

Install tool:

go install github.com/gookit/greq/cmd/greq@latest

Show options:

greq -h

Usage examples:

greq https://httpbin.org/get
greq -X POST -d '{"name": "inhere"}' https://httpbin.org/post
gbench Tool

cmd/gbench Lightweight HTTP request load testing tool similar to ab testing tool

Install tool:

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

Show options:

gbench -h

Usage examples

gbench -c 10 -n 100 https://httpbin.org/get
gbench -c 10 -n 100 -d '{"name": "inhere"}' https://httpbin.org/post

Refers

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.

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

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 send request

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
	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 read body to buffer.

NOTICE: must close resp body.

func (*Response) BodyString

func (r *Response) BodyString() string

BodyString convert response body to string

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 check response body is empty

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) SaveFile added in v0.3.0

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

SaveFile file on the response body is not-nil.

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 command
greq command
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.

Jump to

Keyboard shortcuts

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