package module
v1.0.4 Latest Latest

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

Go to latest
Published: Nov 27, 2017 License: MIT Imports: 24 Imported by: 0



GoDoc Go Report

A http client written with golang


  • directly install
go get -u github.com/iyidan/zrequest
cd $GOPATH/src/mysomeproject
govendor fetch github.com/iyidan/zrequest@v1.0.4


go test github.com/iyidan/zrequest
# go test -v github.com/iyidan/zrequest
  • test with local server(need python environment)
pip install httpbin
pip install gunicorn
go test -local github.com/iyidan/zrequest
# go test -v -local github.com/iyidan/zrequest


See the godoc for more information


package main

import (

// HTTPBinResponse The structure of httpbin response
type HTTPBinResponse struct {
	Args    map[string]string
	Data    string
	Files   map[string]string
	Form    map[string]string
	Headers map[string]string
	JSON    interface{}
	Origin  string
	URL     string `json:"url"`

func main() {
	// the request data
	data := map[string]interface{}{"username": "iyidan","age":22}
	// the response type
	res := HTTPBinResponse{}
	// request and unmarshal response into res
	err := zrequest.Open().SetBody(data).Post("http://httpbin.org/post?arg1=arg1").Unmarshal(&res)
	// handle error
	if err != nil {
	fmt.Printf("The response is: %#v", res)

More Examples: See the test files *_test.go




View Source
const (
	// GET HTTP method
	GET = "GET"

	// POST HTTP method

	// PUT HTTP method
	PUT = "PUT"

	// DELETE HTTP method

	// PATCH HTTP method

	// HEAD HTTP method

	// OPTIONS HTTP method
View Source
const (
	// FlagLogOn determine log on/off
	FlagLogOn = 1 << iota
	// FlagLogDetail determine log type (detail or summary)
	// FlagLogBody determine log request/response body
	// httputil dumpbody into memory
	// So, be careful of the large body request/response


View Source
var (
	HdrUserAgent   = http.CanonicalHeaderKey("User-Agent")
	HdrContentType = http.CanonicalHeaderKey("Content-Type")

	FormBoundary = "FormBoundarykKyzkULVDem6riojjQMsLa2tgA"

	PlainTextType        = "text/plain; charset=utf-8"
	JSONContentType      = "application/json; charset=utf-8"
	FormContentType      = "application/x-www-form-urlencoded"
	MultipartContentType = "multipart/form-data; boundary=" + FormBoundary
	StreamContentType    = "application/octet-stream"

	ErrRequestNotComp = errors.New("resp is nil, request not completed")
View Source
var (
	// TransportWithSSLSkipVerify is the default transport which not auth the ssl server
	TransportWithSSLSkipVerify = &http.Transport{
		Proxy: http.ProxyFromEnvironment,
		Dial: (&net.Dialer{
			Timeout:   30 * time.Second,
			KeepAlive: 30 * time.Second,
		TLSHandshakeTimeout:   10 * time.Second,
		ExpectContinueTimeout: 1 * time.Second,
		TLSClientConfig:       &tls.Config{InsecureSkipVerify: true},

	// DefaultLogger is a logger default used
	DefaultLogger = log.New(os.Stderr, "[zrequest]", 0)


func AnyToString

func AnyToString(i interface{}) string

AnyToString any type parse into string


type Decoder

type Decoder interface {
	Decode(v interface{}) error

Decoder decode response body

type Logger

type Logger interface {
	Println(v ...interface{})
	Printf(format string, v ...interface{})

Logger requests log

type ZClient

type ZClient struct {
	// contains filtered or unexported fields

ZClient wrapped with http client

func NewClient

func NewClient(timeout time.Duration, flags int, logger Logger) *ZClient

NewClient all client share the same http.Transport obj

func NewClientWithHTTPClient

func NewClientWithHTTPClient(hc *http.Client, flags int, logger Logger) *ZClient

NewClientWithHTTPClient wrapped with a exist http client

func NewClientWithSSLSkipVerify

func NewClientWithSSLSkipVerify(timeout time.Duration, flags int, logger Logger) *ZClient

NewClientWithSSLSkipVerify client not auth ssl server

func NewClientWithTransport

func NewClientWithTransport(timeout time.Duration, ts *http.Transport, flags int, logger Logger) *ZClient

NewClientWithTransport wrapped with a exist http transport

func (*ZClient) Open

func (c *ZClient) Open() *ZRequest

Open a request Notice: the request obj should only used in one goroutine

type ZRequest

type ZRequest struct {
	BeforeHookFunc func(*ZRequest) error
	// contains filtered or unexported fields

ZRequest this struct used for a single-http-roundtrip

func Open

func Open() *ZRequest

Open defaultClient

func (*ZRequest) Delete

func (zr *ZRequest) Delete(urlStr string) *ZRequest

Delete request

func (*ZRequest) DisableAtUpload

func (zr *ZRequest) DisableAtUpload() *ZRequest

DisableAtUpload enable '@' prefix to upload a file, default is false

func (*ZRequest) Do

func (zr *ZRequest) Do(method, urlStr string) *ZRequest

Do do a request

func (*ZRequest) Duration

func (zr *ZRequest) Duration() time.Duration

Duration return the request cost time

func (*ZRequest) EnableAtUpload

func (zr *ZRequest) EnableAtUpload() *ZRequest

EnableAtUpload enable '@' prefix to upload a file, default is false

func (*ZRequest) Get

func (zr *ZRequest) Get(urlStr string) *ZRequest

Get request

func (*ZRequest) GetBodyBuf

func (zr *ZRequest) GetBodyBuf() io.Reader

GetBodyBuf get the request bodybuf

func (*ZRequest) GetHeader

func (zr *ZRequest) GetHeader() http.Header

GetHeader get the request header

func (*ZRequest) GetURLStr

func (zr *ZRequest) GetURLStr() string

GetURLStr set the request urlStr

func (*ZRequest) Head

func (zr *ZRequest) Head(urlStr string) *ZRequest

Head request

func (*ZRequest) Options

func (zr *ZRequest) Options(urlStr string) *ZRequest

Options request

func (*ZRequest) Patch

func (zr *ZRequest) Patch(urlStr string) *ZRequest

Patch request

func (*ZRequest) Post

func (zr *ZRequest) Post(urlStr string) *ZRequest

Post request

func (*ZRequest) Put

func (zr *ZRequest) Put(urlStr string) *ZRequest

Put request

func (*ZRequest) Resp

func (zr *ZRequest) Resp() (*http.Response, error)

Resp get raw response , the response.Body is not closed You should close the response body

func (*ZRequest) RespBody

func (zr *ZRequest) RespBody() ([]byte, error)

RespBody response body

func (*ZRequest) RespBodyN

func (zr *ZRequest) RespBodyN(n int64) ([]byte, error)

RespBodyN read response body max n bytes

func (*ZRequest) RespBodyString

func (zr *ZRequest) RespBodyString() (string, error)

RespBodyString response body as string

func (*ZRequest) RespBodyStringN

func (zr *ZRequest) RespBodyStringN(n int64) (string, error)

RespBodyStringN read response body as string with max n bytes

func (*ZRequest) RespCookies

func (zr *ZRequest) RespCookies() []*http.Cookie

RespCookies response cookies

func (*ZRequest) RespHeader

func (zr *ZRequest) RespHeader(key string) string

RespHeader response header

func (*ZRequest) RespHeaders

func (zr *ZRequest) RespHeaders() http.Header

RespHeaders response headers

func (*ZRequest) RespStatus

func (zr *ZRequest) RespStatus() string

RespStatus response status text

func (*ZRequest) RespStatusCode

func (zr *ZRequest) RespStatusCode() int

RespStatusCode response status code

func (*ZRequest) SetBasicAuth

func (zr *ZRequest) SetBasicAuth(username, password string) *ZRequest

SetBasicAuth set a 401 authentication (replace)

func (*ZRequest) SetBody

func (zr *ZRequest) SetBody(body interface{}) *ZRequest

SetBody set the request body

func (*ZRequest) SetBodyBuf

func (zr *ZRequest) SetBodyBuf(buf io.Reader) *ZRequest

SetBodyBuf set the request bodybuf

func (*ZRequest) SetContentType

func (zr *ZRequest) SetContentType(contentType string) *ZRequest

SetContentType set the request Content-Type

func (*ZRequest) SetCookie

func (zr *ZRequest) SetCookie(ck *http.Cookie) *ZRequest

SetCookie set a request cookie (append)

func (*ZRequest) SetCookieString

func (zr *ZRequest) SetCookieString(str string) *ZRequest

SetCookieString set request cookies with given str

func (*ZRequest) SetCookies

func (zr *ZRequest) SetCookies(cks []*http.Cookie) *ZRequest

SetCookies set request cookies

func (*ZRequest) SetHeader

func (zr *ZRequest) SetHeader(key, value string) *ZRequest

SetHeader set a request header

func (*ZRequest) SetHeaders

func (zr *ZRequest) SetHeaders(headers map[string]string) *ZRequest

SetHeaders set multi request header(replace)

func (*ZRequest) SetQueryParam

func (zr *ZRequest) SetQueryParam(key, value string) *ZRequest

SetQueryParam set a query param (replace)

func (*ZRequest) SetQueryParamAny

func (zr *ZRequest) SetQueryParamAny(key string, value interface{}) *ZRequest

SetQueryParamAny set a query params with any type

func (*ZRequest) SetQueryParams

func (zr *ZRequest) SetQueryParams(params map[string]string) *ZRequest

SetQueryParams set query params (replace)

func (*ZRequest) SetQueryParamsAny

func (zr *ZRequest) SetQueryParamsAny(params map[string]interface{}) *ZRequest

SetQueryParamsAny set query params with any type

func (*ZRequest) SetURLStr

func (zr *ZRequest) SetURLStr(urlStr string) *ZRequest

SetURLStr set the request urlStr

func (*ZRequest) SetUserAgent

func (zr *ZRequest) SetUserAgent(ua string) *ZRequest

SetUserAgent set the request ua

func (*ZRequest) Unmarshal

func (zr *ZRequest) Unmarshal(v interface{}) error

Unmarshal unmarshal respone(xml or json) into v

Jump to

Keyboard shortcuts

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