xhttp

package
v0.6.8 Latest Latest
Warning

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

Go to latest
Published: Jan 5, 2022 License: Apache-2.0 Imports: 25 Imported by: 0

README

GoKit - xhttp

HTTP kits for Golang development.

Features

  • Light weight and Easy to use
  • Cookies and Proxy are support
  • Easy use with friendly JSON api
  • Upload and Download file support
  • Debug and Trace info are open
  • Retry request is possible
  • Cache request by method

Installation

go get -u github.com/likexian/gokit

Importing

import (
    "github.com/likexian/gokit/xhttp"
)

Documentation

Visit the docs on GoDoc

Example

The Most easy way
rsp, err := xhttp.Get(context.Background(), "https://www.likexian.com/")
if err != nil {
    panic(err)
}

defer rsp.Close()
text, err := rsp.String()
if err == nil {
    fmt.Println("http status code:", rsp.StatusCode)
    fmt.Println("http response body:", text)
}
Do a Post with form and files
// xhttp.FormParam is form, xhttp.FormFile is file
rsp, err := xhttp.Post(context.Background(), "https://www.likexian.com/",
    xhttp.FormParam{"name": "likexian", "age": 18}, xhttp.FormFile{"file": "README.md"})
if err != nil {
    panic(err)
}

defer rsp.Close()
json, err := rsp.JSON()
if err == nil {
    // http response {"status": {"code": 1, "message": "ok"}}
    code, _ := json.Get("status.code").Int()
    fmt.Println("json status code:", code)
}
Use as Interactive mode
req := xhttp.New()

// set ua and referer
req.SetUA("the new ua")
req.SetReferer("http://the-referer-url.com")

// set tcp connect timeout and client total timeout
req.SetConnectTimeout(3)
req.SetClientTimeout(30)

// not follow 302 and use cookies
req.FollowRedirect(false)
req.EnableCookie(true)

// will send get to https://www.likexian.com/?v=1.0.0
rsp, err := req.Get(context.Background(), "https://www.likexian.com/", xhttp.QueryParam{"v", "1.0.0"})
if err != nil {
    panic(err)
}

// save file as index.html
defer rsp.Close()
_, err := rsp.File("index.html")
if err == nil {
    fmt.Println("Url download as index.html")
}

// use the request param as above
rsp, err := req.Get(context.Background(), "https://www.likexian.com/page/")
if err != nil {
    panic(err)
}

defer rsp.Close()
...
xhttp.Request not thread-safe

This version of xhttp.Request is not thread-safe, please New every thread when doing concurrent

for i := 0; i < 100; i++ {
    go func() {
        // always New one
        req := New()
        rsp, err := req.Do(context.Background(), "GET", LOCALURL)
        if err != nil {
            fmt.Println(err)
            return
        }
        defer rsp.Close()
        str, err := rsp.String()
        if err == nil {
            fmt.Println(str)
        }
    }()
}

License

Copyright 2012-2021 Li Kexian

Licensed under the Apache License 2.0

Donation

If this project is helpful, please share it with friends.

If you want to thank me, you can give me a cup of coffee.

Documentation

Index

Constants

View Source
const Socks5Proxy = "DNSSocks5Proxy"

Variables

View Source
var (
	// DefaultRequest is default request
	DefaultRequest = New()
)

Functions

func Author

func Author() string

Author returns package author

func CheckClient

func CheckClient(r *http.Request, ClientKey string) error

CheckClient returns is a valid client request used by http server, it will check the requestId

func GetClientIPs

func GetClientIPs(r *http.Request) []string

GetClientIPs returns all ips from http client

func GzWrap

func GzWrap(next http.Handler) http.Handler

GzWrap is http gzip transparent compression middleware

func License

func License() string

License returns package license

func SetHeaderWrap

func SetHeaderWrap(next http.Handler, header Header) http.Handler

SetHeaderWrap is http set header middleware

func Version

func Version() string

Version returns package version

Types

type Caching

type Caching struct {
	Method map[string]int64
}

Caching storing cache method and ttl

type Dumping

type Dumping struct {
	DumpHTTP bool
	DumpBody bool
}

Dumping storing http dump setting

type FormFile

type FormFile map[string]string

FormFile is form file for upload, formfield: filename

type FormParam

type FormParam map[string]interface{}

FormParam is form param map pass to xhttp

type Header map[string]string

Header is http request header

type Host

type Host string

Host is http host

type JSONParam

type JSONParam map[string]interface{}

JSONParam is json param map pass to xhttp

type QueryParam

type QueryParam map[string]interface{}

QueryParam is query param map pass to xhttp

type Request

type Request struct {
	ClientID  string
	Request   *http.Request
	Client    *http.Client
	ClientKey string
	Timeout   Timeout
	Caching   Caching
	Retries   Retries
	Dumping   Dumping
}

Request storing request data

func New

func New() (r *Request)

New init a new xhttp client

func (*Request) Delete

func (r *Request) Delete(ctx context.Context, surl string, args ...interface{}) (s *Response, err error)

Delete do http DELETE request and returns response

func (*Request) Do

func (r *Request) Do(ctx context.Context,
	method, surl string, args ...interface{}) (s *Response, err error)

Do send http request and return response

func (*Request) EnableCache

func (r *Request) EnableCache(method string, ttl int64) *Request

EnableCache enable http client cache

func (*Request) EnableCookie

func (r *Request) EnableCookie(enable bool) *Request

EnableCookie set http request enable cookie

func (*Request) FollowRedirect

func (r *Request) FollowRedirect(follow bool) *Request

FollowRedirect set http request follow redirect

func (*Request) Get

func (r *Request) Get(ctx context.Context, surl string, args ...interface{}) (s *Response, err error)

Get do http GET request and returns response

func (*Request) GetHeader

func (r *Request) GetHeader(name string) string

GetHeader return request header value by name

func (*Request) GetTimeout

func (r *Request) GetTimeout() Timeout

GetTimeout get http request timeout

func (*Request) Head

func (r *Request) Head(ctx context.Context, surl string, args ...interface{}) (s *Response, err error)

Head do http HEAD request and returns response

func (*Request) Options

func (r *Request) Options(ctx context.Context, surl string, args ...interface{}) (s *Response, err error)

Options do http OPTIONS request and returns response

func (*Request) Patch

func (r *Request) Patch(ctx context.Context, surl string, args ...interface{}) (s *Response, err error)

Patch do http PATCH request and returns response

func (*Request) Post

func (r *Request) Post(ctx context.Context, surl string, args ...interface{}) (s *Response, err error)

Post do http POST request and returns response

func (*Request) Put

func (r *Request) Put(ctx context.Context, surl string, args ...interface{}) (s *Response, err error)

Put do http PUT request and returns response

func (*Request) SetClientKey

func (r *Request) SetClientKey(key string) *Request

SetClientKey set key for signing requestid

func (*Request) SetClientTimeout

func (r *Request) SetClientTimeout(timeout int) *Request

SetClientTimeout set http client timeout

func (*Request) SetConnectTimeout

func (r *Request) SetConnectTimeout(timeout int) *Request

SetConnectTimeout set http connect timeout

func (*Request) SetDump

func (r *Request) SetDump(dumpHTTP, dumpBody bool) *Request

SetDump set http dump

func (*Request) SetGzip

func (r *Request) SetGzip(gzip bool) *Request

SetGzip set http request gzip

func (*Request) SetHeader

func (r *Request) SetHeader(key, value string) *Request

SetHeader set http request header

func (*Request) SetHost

func (r *Request) SetHost(host string) *Request

SetHost set http request host

func (*Request) SetKeepAliveTimeout

func (r *Request) SetKeepAliveTimeout(timeout int) *Request

SetKeepAliveTimeout set http keepalive timeout

func (*Request) SetProxy

func (r *Request) SetProxy(proxy func(*http.Request) (*url.URL, error)) *Request

SetProxy set http request proxy

func (*Request) SetProxyURL

func (r *Request) SetProxyURL(proxy string) *Request

SetProxyURL set http request proxy url

func (*Request) SetReferer

func (r *Request) SetReferer(referer string) *Request

SetReferer set http request referer

func (*Request) SetRetries

func (r *Request) SetRetries(args ...interface{}) *Request

SetRetries set retry param int arg is setting retry times, time.Duration is setting retry sleep duration 0: no retry (default), -1: retry until success, > 1: retry x times

func (*Request) SetTimeout

func (r *Request) SetTimeout(timeout Timeout) *Request

SetTimeout set http request timeout

func (*Request) SetUA

func (r *Request) SetUA(ua string) *Request

SetUA set http request user-agent

func (*Request) SetVerifyTLS

func (r *Request) SetVerifyTLS(verify bool) *Request

SetVerifyTLS set http request tls verify

type Response

type Response struct {
	Method        string
	URL           *url.URL
	Response      *http.Response
	StatusCode    int
	ContentLength int64
	CacheKey      string
	Tracing       Tracing
	Dumping       [][]byte
}

Response storing response data

func Delete

func Delete(ctx context.Context, surl string, args ...interface{}) (s *Response, err error)

Delete do http DELETE request and returns response

func Get

func Get(ctx context.Context, surl string, args ...interface{}) (s *Response, err error)

Get do http GET request and returns response

func Head(ctx context.Context, surl string, args ...interface{}) (s *Response, err error)

Head do http HEAD request and returns response

func Options

func Options(ctx context.Context, surl string, args ...interface{}) (s *Response, err error)

Options do http OPTIONS request and returns response

func Patch

func Patch(ctx context.Context, surl string, args ...interface{}) (s *Response, err error)

Patch do http PATCH request and returns response

func Post

func Post(ctx context.Context, surl string, args ...interface{}) (s *Response, err error)

Post do http POST request and returns response

func Put

func Put(ctx context.Context, surl string, args ...interface{}) (s *Response, err error)

Put do http PUT request and returns response

func (*Response) Bytes

func (r *Response) Bytes() (b []byte, err error)

Bytes returns response body as bytes

func (*Response) Close

func (r *Response) Close()

Close close response body

func (*Response) Dump

func (r *Response) Dump() [][]byte

Dump returns http dump of request and response [bytes[request], bytes[response]]

func (*Response) File

func (r *Response) File(paths ...string) (size int64, err error)

File save response body to file

func (*Response) GetHeader

func (r *Response) GetHeader(name string) string

GetHeader return response header value by name

func (*Response) JSON

func (r *Response) JSON() (*xjson.JSON, error)

JSON returns response body as *xjson.JSON For more please refer to gokit/xjson

func (*Response) String

func (r *Response) String() (s string, err error)

String returns response body as string

type Retries

type Retries struct {
	Times int
	Sleep time.Duration
}

Retries storing retry setting

type Timeout

type Timeout struct {
	ConnectTimeout        int
	TLSHandshakeTimeout   int
	ResponseHeaderTimeout int
	ExpectContinueTimeout int
	ClientTimeout         int
	KeepAliveTimeout      int
}

Timeout storing timeout setting

type Tracing

type Tracing struct {
	ClientID  string
	RequestID string
	Timestamp string
	Nonce     string
	SendTime  int64
	RecvTime  int64
	Retries   int
}

Tracing storing tracing data

Jump to

Keyboard shortcuts

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