httpc

package
v1.1.8-0...-5ee8a8c Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2021 License: Apache-2.0 Imports: 20 Imported by: 0

README

Http Client

httpc is HTTP client library

install


 go get -u github.com/axfor/bast/httpc

Support for GET POST HEAD POST PUT PATCH DELETE etc.

result support string,json,xml,yaml,file etc.

string result

	result, err := httpc.Get("https://suggest.taobao.com/sug?code=utf-8&q=phone").String()
	if err != nil {
		//handling
	}

json result

	type tb struct {
		Result [][]string `json:"result"`
	}

	rv := &tb{}

	err := httpc.Get("https://suggest.taobao.com/sug?code=utf-8").Param("q", "phone").ToJSON(rv)
	if err != nil {
		//handling
	}

xml result

	type tb struct {
		Result [][]string `json:"result"`
	}

	rv := &tb{}

	err := httpc.Get("https://suggest.taobao.com/sug?code=utf-8").Param("q", "phone").ToXML(rv)
	if err != nil {
		//handling
	}

yaml result

	type tb struct {
		Result [][]string `json:"result"`
	}

	rv := &tb{}

	err := httpc.Get("https://suggest.taobao.com/sug?code=utf-8").Param("q", "phone").ToYAML(rv)
	if err != nil {
		//handling
	}

save result to file

	err := httpc.Post("https://suggest.taobao.com/sug?code=utf-8&q=phone").ToFile("./files/f.json")
	if err != nil {
		//handling
	}

upload file to server

	result, err := httpc.Post("https://suggest.taobao.com/sug?code=utf-8&q=phone").File("testFile", "./files/f.json").String()
	if err != nil {
		//handling
	}

logging and seting title

	type tb struct {
		Result [][]string `json:"result"`
	}

	rv := &tb{}

	err := httpc.Get("https://suggest.taobao.com/sug?code=utf-8").Title("taobao").Logging().Param("q", "phone").ToJSON(rv)
	if err != nil {
		//handling
	}

mark tag and hook's

	result, err := httpc.Post("https://suggest.taobao.com/sug?code=utf-8&q=phone").MarkTag("ai").String()
	if err != nil {
		//handling
	}

Global register hook Before and After


func init() {
	httpc.Before(func(c *httpc.Client) error {
		if c.Tag == "ai" {
			c.Header("xxxx-test-header", "httpc")
		} else {
			//others handling
		}
		return nil
	})

	httpc.After(func(c *httpc.Client) {
		if c.Tag == "ai" && c.OK() {
			//log..
		} else {
			//others handling
		}
	})
} 

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	//DefaultRetries default retries 3
	DefaultRetries = 3
	//DefaultCookieJar default cookie jar
	DefaultCookieJar http.CookieJar
)

Functions

func After

func After(fn func(*Client))

After after handler for each network request

func Before

func Before(fn func(*Client) error)

Before before handler for each network request

func InitDiscovery

func InitDiscovery(discovery *service.Discovery)

InitDiscovery init service discovery

func NewTransport

func NewTransport() *http.Transport

NewTransport new *http.Transport

Types

type Client

type Client struct {
	Req *http.Request

	Conf Settings
	Tag  string
	// contains filtered or unexported fields
}

Client http client

func Delete

func Delete(url string) *Client

Delete returns *Client with Delete method

func Deletes

func Deletes(serviceName string) *Client

Deletes returns *Client with service name ang http delete method

func Get

func Get(url string) *Client

Get issues a GET to the specified URL. If the response is one of the following redirect codes, Get follows the redirect, up to a maximum of 10 redirects:

301 (Moved Permanently)
302 (Found)
303 (See Other)
307 (Temporary Redirect)
308 (Permanent Redirect)

An error is returned if there were too many redirects or if there was an HTTP protocol error. A non-2xx response doesn't cause an error. Any returned error will be of type *url.Error. The url.Error value's Timeout method will report true if request timed out or was canceled.

When err is nil, resp always contains a non-nil resp.Body. Caller should close resp.Body when done reading from it.

Get is a wrapper around DefaultClient.Get.

To make a request with custom headers, use NewRequest and DefaultClient.Do.

func Gets

func Gets(serviceName string) *Client

Gets returns *Client with service name ang http get method

func Head(url string) *Client

Head issues a HEAD to the specified URL. If the response is one of the following redirect codes, Head follows the redirect, up to a maximum of 10 redirects:

301 (Moved Permanently)
302 (Found)
303 (See Other)
307 (Temporary Redirect)
308 (Permanent Redirect)

Head is a wrapper around DefaultClient.Head

func Heads

func Heads(serviceName string) *Client

Heads returns *Client with service name ang http head method

func Patch

func Patch(url string) *Client

Patch returns *Client with Patch method

func Patchs

func Patchs(serviceName string) *Client

Patchs returns *Client with service name ang http patch method

func Post

func Post(url string) *Client

Post issues a POST to the specified URL.

Caller should close resp.Body when done reading from it.

If the provided body is an io.Closer, it is closed after the request.

Post is a wrapper around DefaultClient.Post.

To set custom headers, use NewRequest and DefaultClient.Do.

See the Client.Do method documentation for details on how redirects are handled.

func Posts

func Posts(serviceName string) *Client

Posts returns *Client with service name ang http post method

func Put

func Put(url string) *Client

Put returns *Client with PUT method

func Puts

func Puts(serviceName string) *Client

Puts returns *Client with service name ang http put method

func Service

func Service(serviceName, method string) *Client

Service returns *Client with service name ang http xxx method

func (*Client) Accept

func (c *Client) Accept(accept string) *Client

Accept sets Accept header field

func (*Client) Body

func (c *Client) Body(data interface{}) *Client

Body adds request raw body.

func (*Client) BodyWithContentType

func (c *Client) BodyWithContentType(data []byte, contentType string) *Client

BodyWithContentType adds request raw body encoding by XML.

func (*Client) Bytes

func (c *Client) Bytes() ([]byte, error)

Bytes returns the body []byte in response. it calls Response inner.

func (*Client) CheckRedirect

func (c *Client) CheckRedirect(checkRedirect func(req *http.Request, via []*http.Request) error) *Client

CheckRedirect proxy method http.Get

func (*Client) Clear

func (c *Client) Clear() *Client

Clear all response data

func (*Client) Client

func (c *Client) Client(client *http.Client) *Client

Client set http.Client

func (*Client) Cookie

func (c *Client) Cookie(cookie *http.Cookie) *Client

Cookie add cookie into request.

func (*Client) Do

func (c *Client) Do() (resp *http.Response, err error)

Do add files into request

func (*Client) EnableCookie

func (c *Client) EnableCookie(enableCookie bool) *Client

EnableCookie set enable cookie jar

func (*Client) Error

func (c *Client) Error() error

func (*Client) File

func (c *Client) File(fileName, path string) *Client

File add file into request.

func (*Client) Files

func (c *Client) Files(paths map[string]string) *Client

Files add files into request.

func (*Client) HasError

func (c *Client) HasError() bool

HasError has error

func (*Client) Header

func (c *Client) Header(key, value string) *Client

Header add header item string in request.

func (*Client) JSONBody

func (c *Client) JSONBody(obj interface{}) *Client

JSONBody adds request raw body encoding by JSON.

func (*Client) JSONBodyWithError

func (c *Client) JSONBodyWithError(obj interface{}) (*Client, error)

JSONBodyWithError adds request raw body encoding by JSON.

func (*Client) Jar

func (c *Client) Jar(jar http.CookieJar) *Client

Jar proxy method http.Get

func (*Client) Logging

func (c *Client) Logging() *Client

Logging set log

func (*Client) MarkTag

func (c *Client) MarkTag(tag string) *Client

MarkTag sets an tag field

func (*Client) OK

func (c *Client) OK() bool

OK status code is 200

func (*Client) Param

func (c *Client) Param(key string, value interface{}) *Client

Param adds query param in to request. params build query string as ?key1=value1&key2=value2...

func (*Client) Params

func (c *Client) Params(values url.Values) *Client

Params adds query param in to request. params build query string as ?key1=value1&key2=value2...

func (*Client) Request

func (c *Client) Request(request *http.Request) *Client

Request set http.Request

func (*Client) Result

func (c *Client) Result(v interface{}) error

Result returns the map that marshals from the body bytes as json or xml or yaml in response . default json

func (*Client) Retries

func (c *Client) Retries(retries int) *Client

Retries maximum retries count

func (*Client) SetBasicAuth

func (c *Client) SetBasicAuth(username, password string) *Client

SetBasicAuth sets the request's 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.

Some protocols may impose additional requirements on pre-escaping the username and password. For instance, when used with OAuth2, both arguments must be URL encoded first with url.QueryEscape.

func (*Client) Settings

func (c *Client) Settings(settings Settings) *Client

Settings set settings If nil, DefaultSettings is used.

func (*Client) String

func (c *Client) String() (string, error)

func (*Client) Title

func (c *Client) Title(title string) *Client

Title set title

func (*Client) ToFile

func (c *Client) ToFile(filename string) error

ToFile saves the body data in response to one file. it calls Response inner.

func (*Client) ToJSON

func (c *Client) ToJSON(v interface{}) error

ToJSON returns the map that marshals from the body bytes as json in response . it calls Response inner.

func (*Client) ToMap

func (c *Client) ToMap(v *map[string]interface{}) error

ToMap returns the map that marshals from the body bytes as json in response . it calls Response inner.

func (*Client) ToXML

func (c *Client) ToXML(v interface{}) error

ToXML returns the map that marshals from the body bytes as xml in response . it calls Response inner.

func (*Client) ToYAML

func (c *Client) ToYAML(v interface{}) error

ToYAML returns the map that marshals from the body bytes as yaml in response . it calls Response inner.

func (*Client) Transport

func (c *Client) Transport(transport http.RoundTripper) *Client

Transport specifies the mechanism by which individual HTTP requests are made. If nil, DefaultTransport is used.

func (*Client) Unlogging

func (c *Client) Unlogging() *Client

Unlogging unset log

func (*Client) UserAgent

func (c *Client) UserAgent(useragent string) *Client

UserAgent sets User-Agent header field

func (*Client) XMLBody

func (c *Client) XMLBody(obj interface{}) *Client

XMLBody adds request raw body encoding by XML.

func (*Client) XMLBodyWithError

func (c *Client) XMLBodyWithError(obj interface{}) (*Client, error)

XMLBodyWithError adds request raw body encoding by XML.

func (*Client) YAMLBody

func (c *Client) YAMLBody(obj interface{}) *Client

YAMLBody adds request raw body encoding by YAML.

func (*Client) YAMLBodyWithError

func (c *Client) YAMLBodyWithError(obj interface{}) (*Client, error)

YAMLBodyWithError adds request raw body encoding by YAML.

type Settings

type Settings struct {
	Transport       http.RoundTripper
	EnableCookie    bool
	Retry           int
	Log             bool
	Title, LogTitle string
}

Settings of Client

Jump to

Keyboard shortcuts

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