httplib

package
v1.0.14 Latest Latest
Warning

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

Go to latest
Published: Feb 9, 2022 License: LGPL-3.0 Imports: 21 Imported by: 0

README

httplib

httplib is an libs help you to curl remote url.

How to use?

GET

you can use Get to crawl data.

import "github.com/W3-Engineers-Ltd/Radiant/client/httplib"

str, err := httplib.Get("http://radiant.me/").String()
if err != nil {
    	// error
}
fmt.Println(str)

POST

POST data to remote url

req := httplib.Post("http://radiant.me/")
req.Param("username","astaxie")
req.Param("password","123456")
str, err := req.String()
if err != nil {
    	// error
}
fmt.Println(str)

Set timeout

The default timeout is 60 seconds, function prototype:

SetTimeout(connectTimeout, readWriteTimeout time.Duration)

Example:

// GET
httplib.Get("http://radiant.me/").SetTimeout(100 * time.Second, 30 * time.Second)

// POST
httplib.Post("http://radiant.me/").SetTimeout(100 * time.Second, 30 * time.Second)

Debug

If you want to debug the request info, set the debug on

httplib.Get("http://radiant.me/").Debug(true)

Set HTTP Basic Auth

str, err := Get("http://radiant.me/").SetBasicAuth("user", "passwd").String()
if err != nil {
    	// error
}
fmt.Println(str)

Set HTTPS

If request url is https, You can set the client support TSL:

httplib.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})

More info about the tls.Config please visit http://golang.org/pkg/crypto/tls/#Config

Set HTTP Version

some servers need to specify the protocol version of HTTP

httplib.Get("http://radiant.me/").SetProtocolVersion("HTTP/1.1")

some http request need setcookie. So set it like this:

cookie := &http.Cookie{}
cookie.Name = "username"
cookie.Value  = "astaxie"
httplib.Get("http://radiant.me/").SetCookie(cookie)

Upload file

httplib support mutil file upload, use req.PostFile()

req := httplib.Post("http://radiant.me/")
req.Param("username","astaxie")
req.PostFile("uploadfile1", "httplib.pdf")
str, err := req.String()
if err != nil {
    	// error
}
fmt.Println(str)

See godoc for further documentation and examples.

Documentation

Overview

Package httplib is used as http.Client Usage:

import "github.com/W3-Engineers-Ltd/Radiant/client/httplib"

	b := httplib.Post("http://radiant.me/")
	b.Param("username","astaxie")
	b.Param("password","123456")
	b.PostFile("uploadfile1", "httplib.pdf")
	b.PostFile("uploadfile2", "httplib.txt")
	str, err := b.String()
	if err != nil {
		t.Fatal(err)
	}
	fmt.Println(str)

 more docs http://radiant.me/docs/module/httplib.md

Index

Constants

This section is empty.

Variables

View Source
var CloseFileFailed = berror.DefineCode(5001004, moduleName, "CloseFileFailed", `
After handling files, Radiant try to close file but failed. Usually it was caused by bad file descriptor.
`)
View Source
var CopyFileFailed = berror.DefineCode(5001003, moduleName, "CopyFileFailed", `
When we try to read file content and then copy it to another writer, and failed.
1. Unexpected EOF;
2. Bad file descriptor;
3. Write conflict;

Please check your file content, and confirm that file is not processed by other process (or by user manually).
`)
View Source
var CreateFileIfNotExistFailed = berror.DefineCode(5001007, moduleName, "CreateFileIfNotExist", `
Radiant want to create file if not exist and failed. 
In most cases, it means that Radiant doesn't have the privilege to create this file.
Please change file mode to ensure that Radiant is able to create files on specific directory.
Or you can run Radiant with higher authority.
In some cases, you pass invalid filename. Make sure that the file name is valid on your system.
`)
View Source
var CreateFormFileFailed = berror.DefineCode(5001001, moduleName, "CreateFormFileFailed", `
In normal case than handling files with RadiantRequest, you should not see this error code.
Unexpected EOF, invalid characters, bad file descriptor may cause this error.
`)
View Source
var InvalidJSONBody = berror.DefineCode(4001006, moduleName, "InvalidJSONBody", `
You pass invalid data which could not be converted to JSON documents. In general, if you pass structure, it works well.
Sometimes you got JSON document and you want to make it as request body. So you call JSONBody.
If you do this, you got this code. Instead, you should call Header to set Content-type and call Body to set body data.
`)
View Source
var InvalidUrl = berror.DefineCode(4001001, moduleName, "InvalidUrl", `
You pass a invalid url to httplib module. Please check your url, be careful about special character. 
`)
View Source
var InvalidUrlProtocolVersion = berror.DefineCode(4001002, moduleName, "InvalidUrlProtocolVersion", `
You pass a invalid protocol version. In practice, we use HTTP/1.0, HTTP/1.1, HTTP/1.2
But something like HTTP/3.2 is valid for client, and the major version is 3, minor version is 2.
but you must confirm that server support those abnormal protocol version.
`)
View Source
var InvalidXMLBody = berror.DefineCode(4001004, moduleName, "InvalidXMLBody", `
You pass invalid data which could not be converted to XML documents. In general, if you pass structure, it works well.
Sometimes you got XML document and you want to make it as request body. So you call XMLBody.
If you do this, you got this code. Instead, you should call Header to set Content-type and call Body to set body data.
`)
View Source
var InvalidYAMLBody = berror.DefineCode(4001005, moduleName, "InvalidYAMLBody", `
You pass invalid data which could not be converted to YAML documents. In general, if you pass structure, it works well.
Sometimes you got YAML document and you want to make it as request body. So you call YAMLBody.
If you do this, you got this code. Instead, you should call Header to set Content-type and call Body to set body data.
`)
View Source
var ReadFileFailed = berror.DefineCode(5001002, moduleName, "ReadFileFailed", `
There are several cases that cause this error:
1. file not found. Please check the file name;
2. file not found, but file name is correct. If you use relative file path, it's very possible for you to see this code.
make sure that this file is in correct directory which Radiant looks for;
3. Radiant don't have the privilege to read this file, please change file mode; 
`)
View Source
var ReadGzipBodyFailed = berror.DefineCode(5001006, moduleName, "BuildGzipReaderFailed", `
Radiant parse gzip-encode body failed. Usually Radiant got invalid response.
Please confirm that server returns gzip data.
`)
View Source
var SendRequestFailed = berror.DefineCode(5001005, moduleName, "SendRequestRetryExhausted", `
Radiant send HTTP request, but it failed.
If you config retry times, it means that Radiant had retried and failed.
When you got this error, there are vary kind of reason:
1. Network unstable and timeout. In this case, sometimes server has received the request.
2. Server error. Make sure that server works well.
3. The request is invalid, which means that you pass some invalid parameter.
`)
View Source
var UnmarshalJSONResponseToObjectFailed = berror.DefineCode(5001008, moduleName,
	"UnmarshalResponseToObjectFailed", `
Radiant trying to unmarshal response's body to structure but failed.
Make sure that:
1. You pass valid structure pointer to the function;
2. The body is valid json document
`)
View Source
var UnmarshalResponseToObjectFailed = berror.DefineCode(5001011, moduleName,
	"UnmarshalResponseToObjectFailed", `
Radiant trying to unmarshal response's body to structure but failed.
There are several cases that cause this error:
1. You pass valid structure pointer to the function;
2. The body is valid json, Yaml or XML document
`)
View Source
var UnmarshalXMLResponseToObjectFailed = berror.DefineCode(5001009, moduleName,
	"UnmarshalResponseToObjectFailed", `
Radiant trying to unmarshal response's body to structure but failed.
Make sure that:
1. You pass valid structure pointer to the function;
2. The body is valid XML document
`)
View Source
var UnmarshalYAMLResponseToObjectFailed = berror.DefineCode(5001010, moduleName,
	"UnmarshalResponseToObjectFailed", `
Radiant trying to unmarshal response's body to structure but failed.
Make sure that:
1. You pass valid structure pointer to the function;
2. The body is valid YAML document
`)
View Source
var UnsupportedBodyType = berror.DefineCode(4001003, moduleName, "UnsupportedBodyType", `
You use a invalid data as request body.
For now, we only support type string and byte[].
`)

Functions

func AddDefaultFilter

func AddDefaultFilter(fc FilterChain)

AddDefaultFilter add a new filter into defaultSetting Be careful about using this method if you invoke SetDefaultSetting somewhere

func NewHttpResponseWithJsonBody

func NewHttpResponseWithJsonBody(data interface{}) *http.Response

NewHttpResponseWithJsonBody will try to convert the data to json format usually you only use this when you want to mock http Response

func SetDefaultSetting

func SetDefaultSetting(setting RadiantHTTPSettings)

SetDefaultSetting overwrites default settings Keep in mind that when you invoke the SetDefaultSetting some methods invoked before SetDefaultSetting

func TimeoutDialer

func TimeoutDialer(cTimeout time.Duration, rwTimeout time.Duration) func(net, addr string) (c net.Conn, err error)

TimeoutDialer returns functions of connection dialer with timeout settings for http.Transport Dial field. Deprecated we will move this at the end of 2021 please use TimeoutDialerCtx

func TimeoutDialerCtx

func TimeoutDialerCtx(cTimeout time.Duration,
	rwTimeout time.Duration) func(ctx context.Context, net, addr string) (c net.Conn, err error)

Types

type Client

type Client struct {
	Name       string
	Endpoint   string
	CommonOpts []RadiantHTTPRequestOption

	Setting RadiantHTTPSettings
}

Client provides an HTTP client supporting chain call

func NewClient

func NewClient(name string, endpoint string, opts ...ClientOption) (*Client, error)

NewClient return a new http client

func (*Client) Delete

func (c *Client) Delete(value interface{}, path string, opts ...RadiantHTTPRequestOption) error

Delete Send a Delete request and try to give its result value

func (*Client) Get

func (c *Client) Get(value interface{}, path string, opts ...RadiantHTTPRequestOption) error

Get Send a GET request and try to give its result value

func (*Client) Head

func (c *Client) Head(value interface{}, path string, opts ...RadiantHTTPRequestOption) error

Head Send a Head request and try to give its result value

func (*Client) Post

func (c *Client) Post(value interface{}, path string, body interface{}, opts ...RadiantHTTPRequestOption) error

Post Send a POST request and try to give its result value

func (*Client) Put

func (c *Client) Put(value interface{}, path string, body interface{}, opts ...RadiantHTTPRequestOption) error

Put Send a Put request and try to give its result value

type ClientOption

type ClientOption func(client *Client)

func WithCheckRedirect

func WithCheckRedirect(redirect func(req *http.Request, via []*http.Request) error) ClientOption

WithCheckRedirect will specifies the policy for handling redirects in all subsequent request

func WithEnableCookie

func WithEnableCookie(enable bool) ClientOption

WithEnableCookie will enable cookie in all subsequent request

func WithEnableGzip

func WithEnableGzip(enable bool) ClientOption

WithEnableGzip will enable gzip in all subsequent request

func WithHTTPSetting

func WithHTTPSetting(setting RadiantHTTPSettings) ClientOption

WithHTTPSetting can replace radiantHTTPSeting

func WithProxy

func WithProxy(proxy func(*http.Request) (*url.URL, error)) ClientOption

WithProxy will set http proxy field in all subsequent request

func WithTLSClientConfig

func WithTLSClientConfig(config *tls.Config) ClientOption

WithTLSClientConfig will adds tls config in all subsequent request

func WithTransport

func WithTransport(transport http.RoundTripper) ClientOption

WithTransport will set transport field in all subsequent request

func WithUserAgent

func WithUserAgent(userAgent string) ClientOption

WithEnableCookie will adds UA in all subsequent request

type Filter

type Filter func(ctx context.Context, req *RadiantHTTPRequest) (*http.Response, error)

type FilterChain

type FilterChain func(next Filter) Filter

type HTTPBodyCarrier

type HTTPBodyCarrier interface {
	SetReader(r io.ReadCloser)
}

HTTPBodyCarrier If value implement HTTPBodyCarrier. http.Response.Body will pass to SetReader

type HTTPBytesCarrier

type HTTPBytesCarrier interface {
	SetBytes(bytes []byte)
}

HTTPBytesCarrier If value implement HTTPBytesCarrier. All the byte in http.Response.Body will pass to SetBytes

type HTTPHeadersCarrier

type HTTPHeadersCarrier interface {
	SetHeader(header map[string][]string)
}

HttpHeaderCarrier If value implement HttpHeaderCarrier. http.Response.Header will pass to SetHeader

type HTTPResponseCarrier

type HTTPResponseCarrier interface {
	SetHTTPResponse(resp *http.Response)
}

HTTPResponseCarrier If value implement HTTPResponseCarrier. http.Response will pass to SetHTTPResponse

type HTTPStatusCarrier

type HTTPStatusCarrier interface {
	SetStatusCode(status int)
}

HTTPStatusCarrier If value implement HTTPStatusCarrier. http.Response.StatusCode will pass to SetStatusCode

type RadiantHTTPRequest

type RadiantHTTPRequest struct {
	// contains filtered or unexported fields
}

RadiantHTTPRequest provides more useful methods than http.Request for requesting a url.

func Delete

func Delete(url string) *RadiantHTTPRequest

Delete returns *RadiantHttpRequest DELETE method.

func Get

func Get(url string) *RadiantHTTPRequest

Get returns *RadiantHttpRequest with GET method.

func Head(url string) *RadiantHTTPRequest

Head returns *RadiantHttpRequest with HEAD method.

func NewRadiantRequest

func NewRadiantRequest(rawurl, method string) *RadiantHTTPRequest

NewRadiantRequest returns *RadiantHttpRequest with specific method TODO add error as return value I think if we don't return error users are hard to check whether we create Radiant request successfully

func Post

func Post(url string) *RadiantHTTPRequest

Post returns *RadiantHttpRequest with POST method.

func Put

func Put(url string) *RadiantHTTPRequest

Put returns *RadiantHttpRequest with PUT method.

func (*RadiantHTTPRequest) AddFilters

func (b *RadiantHTTPRequest) AddFilters(fcs ...FilterChain) *RadiantHTTPRequest

AddFilters adds filter

func (*RadiantHTTPRequest) Body

func (b *RadiantHTTPRequest) Body(data interface{}) *RadiantHTTPRequest

Body adds request raw body. Supports string and []byte. TODO return error if data is invalid

func (*RadiantHTTPRequest) Bytes

func (b *RadiantHTTPRequest) Bytes() ([]byte, error)

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

func (*RadiantHTTPRequest) DoRequest

func (b *RadiantHTTPRequest) DoRequest() (resp *http.Response, err error)

DoRequest executes client.Do

func (*RadiantHTTPRequest) DoRequestWithCtx

func (b *RadiantHTTPRequest) DoRequestWithCtx(ctx context.Context) (resp *http.Response, err error)

func (*RadiantHTTPRequest) GetRequest

func (b *RadiantHTTPRequest) GetRequest() *http.Request

GetRequest returns the request object

func (*RadiantHTTPRequest) Header

func (b *RadiantHTTPRequest) Header(key, value string) *RadiantHTTPRequest

Header adds header item string in request.

func (*RadiantHTTPRequest) JSONBody

func (b *RadiantHTTPRequest) JSONBody(obj interface{}) (*RadiantHTTPRequest, error)

JSONBody adds the request raw body encoded in JSON.

func (*RadiantHTTPRequest) JSONMarshal

func (b *RadiantHTTPRequest) JSONMarshal(obj interface{}) ([]byte, error)

func (*RadiantHTTPRequest) Param

func (b *RadiantHTTPRequest) Param(key, value string) *RadiantHTTPRequest

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

func (*RadiantHTTPRequest) PostFile

func (b *RadiantHTTPRequest) PostFile(formname, filename string) *RadiantHTTPRequest

PostFile adds a post file to the request

func (*RadiantHTTPRequest) Response

func (b *RadiantHTTPRequest) Response() (*http.Response, error)

Response executes request client gets response manually.

func (*RadiantHTTPRequest) Retries

func (b *RadiantHTTPRequest) Retries(times int) *RadiantHTTPRequest

Retries sets Retries times. default is 0 (never retry) -1 retry indefinitely (forever) Other numbers specify the exact retry amount

func (*RadiantHTTPRequest) RetryDelay

func (b *RadiantHTTPRequest) RetryDelay(delay time.Duration) *RadiantHTTPRequest

RetryDelay sets the time to sleep between reconnection attempts

func (*RadiantHTTPRequest) SetBasicAuth

func (b *RadiantHTTPRequest) SetBasicAuth(username, password string) *RadiantHTTPRequest

SetBasicAuth sets the request's Authorization header to use HTTP Basic Authentication with the provided username and password.

func (*RadiantHTTPRequest) SetCheckRedirect

func (b *RadiantHTTPRequest) SetCheckRedirect(redirect func(req *http.Request, via []*http.Request) error) *RadiantHTTPRequest

SetCheckRedirect specifies the policy for handling redirects.

If CheckRedirect is nil, the Client uses its default policy, which is to stop after 10 consecutive requests.

func (*RadiantHTTPRequest) SetCookie

func (b *RadiantHTTPRequest) SetCookie(cookie *http.Cookie) *RadiantHTTPRequest

SetCookie adds a cookie to the request.

func (*RadiantHTTPRequest) SetEnableCookie

func (b *RadiantHTTPRequest) SetEnableCookie(enable bool) *RadiantHTTPRequest

SetEnableCookie sets enable/disable cookiejar

func (*RadiantHTTPRequest) SetEscapeHTML

func (b *RadiantHTTPRequest) SetEscapeHTML(isEscape bool) *RadiantHTTPRequest

SetEscapeHTML is used to set the flag whether escape HTML special characters during processing

func (*RadiantHTTPRequest) SetFilters

func (b *RadiantHTTPRequest) SetFilters(fcs ...FilterChain) *RadiantHTTPRequest

SetFilters will use the filter as the invocation filters

func (*RadiantHTTPRequest) SetHost

func (b *RadiantHTTPRequest) SetHost(host string) *RadiantHTTPRequest

SetHost set the request host

func (*RadiantHTTPRequest) SetProtocolVersion

func (b *RadiantHTTPRequest) SetProtocolVersion(vers string) *RadiantHTTPRequest

SetProtocolVersion sets the protocol version for incoming requests. Client requests always use HTTP/1.1

func (*RadiantHTTPRequest) SetProxy

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

SetProxy sets the HTTP proxy example:

func(req *http.Request) (*url.URL, error) {
	u, _ := url.ParseRequestURI("http://127.0.0.1:8118")
	return u, nil
}

func (*RadiantHTTPRequest) SetTLSClientConfig

func (b *RadiantHTTPRequest) SetTLSClientConfig(config *tls.Config) *RadiantHTTPRequest

SetTLSClientConfig sets TLS connection configuration if visiting HTTPS url.

func (*RadiantHTTPRequest) SetTimeout

func (b *RadiantHTTPRequest) SetTimeout(connectTimeout, readWriteTimeout time.Duration) *RadiantHTTPRequest

SetTimeout sets connect time out and read-write time out for RadiantRequest.

func (*RadiantHTTPRequest) SetTransport

func (b *RadiantHTTPRequest) SetTransport(transport http.RoundTripper) *RadiantHTTPRequest

SetTransport sets the transport field

func (*RadiantHTTPRequest) SetUserAgent

func (b *RadiantHTTPRequest) SetUserAgent(useragent string) *RadiantHTTPRequest

SetUserAgent sets User-Agent header field

func (*RadiantHTTPRequest) Setting

Setting changes request settings

func (*RadiantHTTPRequest) String

func (b *RadiantHTTPRequest) String() (string, error)

String returns the body string in response. Calls Response inner.

func (*RadiantHTTPRequest) ToFile

func (b *RadiantHTTPRequest) ToFile(filename string) error

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

func (*RadiantHTTPRequest) ToJSON

func (b *RadiantHTTPRequest) ToJSON(v interface{}) error

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

func (*RadiantHTTPRequest) ToValue

func (b *RadiantHTTPRequest) ToValue(value interface{}) error

ToValue attempts to resolve the response body to value using an existing method. Calls Response inner. If response header contain Content-Type, func will call ToJSON\ToXML\ToYAML. Else it will try to parse body as json\yaml\xml, If all attempts fail, an error will be returned

func (*RadiantHTTPRequest) ToXML

func (b *RadiantHTTPRequest) ToXML(v interface{}) error

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

func (*RadiantHTTPRequest) ToYAML

func (b *RadiantHTTPRequest) ToYAML(v interface{}) error

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

func (*RadiantHTTPRequest) XMLBody

func (b *RadiantHTTPRequest) XMLBody(obj interface{}) (*RadiantHTTPRequest, error)

XMLBody adds the request raw body encoded in XML.

func (*RadiantHTTPRequest) YAMLBody

func (b *RadiantHTTPRequest) YAMLBody(obj interface{}) (*RadiantHTTPRequest, error)

YAMLBody adds the request raw body encoded in YAML.

type RadiantHTTPRequestOption

type RadiantHTTPRequestOption func(request *RadiantHTTPRequest)

func WithBasicAuth

func WithBasicAuth(basicAuth func() (string, string)) RadiantHTTPRequestOption

WithBasicAuth adds a custom function to set basic auth

func WithContentType

func WithContentType(contentType string) RadiantHTTPRequestOption

WithContentType adds ContentType in header

func WithCookie

func WithCookie(cookie *http.Cookie) RadiantHTTPRequestOption

WithCookie adds a cookie to the request.

func WithFilters

func WithFilters(fcs ...FilterChain) RadiantHTTPRequestOption

WithFilters will use the filter as the invocation filters

func WithHeader

func WithHeader(key, value string) RadiantHTTPRequestOption

WithHeader adds header item string in request.

func WithParam

func WithParam(key, value string) RadiantHTTPRequestOption

WithParam adds query param in to request.

func WithRetry

func WithRetry(times int, delay time.Duration) RadiantHTTPRequestOption

WithRetry set retry times and delay for the request default is 0 (never retry) -1 retry indefinitely (forever) Other numbers specify the exact retry amount

func WithTimeout

func WithTimeout(connectTimeout, readWriteTimeout time.Duration) RadiantHTTPRequestOption

WithTimeout sets connect time out and read-write time out for RadiantRequest.

func WithTokenFactory

func WithTokenFactory(tokenFactory func() string) RadiantHTTPRequestOption

Withtokenfactory adds a custom function to set Authorization

type RadiantHTTPSettings

type RadiantHTTPSettings struct {
	UserAgent        string
	ConnectTimeout   time.Duration
	ReadWriteTimeout time.Duration
	TLSClientConfig  *tls.Config
	Proxy            func(*http.Request) (*url.URL, error)
	Transport        http.RoundTripper
	CheckRedirect    func(req *http.Request, via []*http.Request) error
	EnableCookie     bool
	Gzip             bool
	Retries          int // if set to -1 means will retry forever
	RetryDelay       time.Duration
	FilterChains     []FilterChain
	EscapeHTML       bool // if set to false means will not escape escape HTML special characters during processing, default true
}

RadiantHTTPSettings is the http.Client setting

func GetDefaultSetting

func GetDefaultSetting() RadiantHTTPSettings

GetDefaultSetting return current default setting

Directories

Path Synopsis
filter
log

Jump to

Keyboard shortcuts

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