dhttp

package
v1.7.16 Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2023 License: MIT Imports: 30 Imported by: 0

Documentation

Overview

Package HttpClient is a simplified http client. Its initial codes are cloned from [HttpRequest](https://github.com/parnurzeal/gorequest). I have refactored the codes and make it more friendly to programmers. HttpClient makes http thing more simple for you, using fluent styles to make http client more awesome. You can control headers, timeout, query parameters, binding response and others in one line:

Before

client := &http.Client{
	 CheckRedirect: redirectPolicyFunc,
}

req, err := http.NewRequest("GET", "http://example.com", nil) req.Header.Add("If-None-Match", `W/"wyzzy"`) resp, err := client.Do(req)

Using HttpClient

resp, body, errs := dhttp.New().Get("http://example.com").

RedirectPolicy(redirectPolicyFunc).
SetHeader("If-None-Match", `W/"wyzzy"`).
End()

Index

Constants

View Source
const (
	POST    = "POST"
	GET     = "GET"
	HEAD    = "HEAD"
	PUT     = "PUT"
	DELETE  = "DELETE"
	PATCH   = "PATCH"
	OPTIONS = "OPTIONS"
)

HTTP methods we support

View Source
const (
	TypeJSON       = "json"
	TypeXML        = "xml"
	TypeUrlencoded = "urlencoded"
	TypeForm       = "form"
	TypeFormData   = "form-data"
	TypeHTML       = "html"
	TypeText       = "text"
	TypeMultipart  = "multipart"
)

Types we support.

View Source
const (
	RemoteIP        = "remote_ip"
	Ret             = "ret"
	RwtRawStr       = "ret_raw_str"
	Code            = "code"
	Err             = "err"
	SessionLogLevel = "session_log_level"
	Debug           = "debug"
	Data            = "data"
	DataRaw         = "data_raw"
	RedirectUrl     = "redirect_url"
	TraceID         = "trace_id"
	GdToken         = "gd_token"
)

Variables

View Source
var DisableTransportSwap = false
View Source
var Types = map[string]string{
	TypeJSON:       "application/json",
	TypeXML:        "application/xml",
	TypeForm:       "application/x-www-form-urlencoded",
	TypeFormData:   "application/x-www-form-urlencoded",
	TypeUrlencoded: "application/x-www-form-urlencoded",
	TypeHTML:       "text/html",
	TypeText:       "text/plain",
	TypeMultipart:  "multipart/form-data",
}

Functions

func CheckWrap added in v1.6.5

func CheckWrap(toWrap interface{}) error

func GlFilter

func GlFilter() gin.HandlerFunc

use gl

func GroupFilter

func GroupFilter() gin.HandlerFunc

group filter

func Logger

func Logger(pk string) gin.HandlerFunc

log middle handle

func ParseRet

func ParseRet(c *gin.Context) (ret interface{}, origErr interface{})

func Return

func Return(c *gin.Context, code int, message string, err error, result interface{})

func StatFilter added in v1.6.4

func StatFilter() gin.HandlerFunc

stat filter

func Wrap

func Wrap(toWrap interface{}) gin.HandlerFunc

example: wrap to gin.HandlerFunc -- func(*Context)

Types

type File added in v1.7.6

type File struct {
	Filename  string
	Fieldname string
	Data      []byte
}

type HttpClient

type HttpClient struct {
	Url                  string
	Method               string
	Header               http.Header
	TargetType           string
	ForceType            string
	Data                 map[string]interface{}
	SliceData            []interface{}
	FormData             url.Values
	QueryData            url.Values
	FileData             []File
	BounceToRawString    bool
	RawString            string
	Client               *http.Client
	Transport            *http.Transport
	Cookies              []*http.Cookie
	Errors               []error
	BasicAuth            struct{ Username, Password string }
	Debug                bool
	CurlCommand          bool
	Retryable            HttpClientRetryable
	DoNotClearHttpClient bool
	// contains filtered or unexported fields
}

A HttpClient is a object storing all request data for client.

func New added in v1.7.6

func New() *HttpClient

Used to create a new HttpClient object.

func (*HttpClient) AddCookie added in v1.7.6

func (dhc *HttpClient) AddCookie(c *http.Cookie) *HttpClient

AddCookie adds a cookie to the request. The behavior is the same as AddCookie on Request from net/http

func (*HttpClient) AddCookies added in v1.7.6

func (dhc *HttpClient) AddCookies(cookies []*http.Cookie) *HttpClient

AddCookies is a convenient method to add multiple cookies

func (*HttpClient) AppendHeader added in v1.7.6

func (dhc *HttpClient) AppendHeader(param string, value string) *HttpClient

AppendHeader is used for setting header fileds with multiple values, Example. To set `Accept` as `application/json, text/plain`

New().
  Post("/gamelist").
  AppendHeader("Accept", "application/json").
  AppendHeader("Accept", "text/plain").
  End()

func (*HttpClient) AsCurlCommand added in v1.7.6

func (dhc *HttpClient) AsCurlCommand() (string, error)

AsCurlCommand returns a string representing the runnable `curl' command version of the request.

func (*HttpClient) ClearHttpClient added in v1.7.6

func (dhc *HttpClient) ClearHttpClient()

Clear HttpClient data for another new request.

func (*HttpClient) Clone added in v1.7.6

func (dhc *HttpClient) Clone() *HttpClient

Returns a copy of this HttpClient. Useful if you want to reuse the client/settings concurrently. Note: This does a shallow copy of the parent. So you will need to be careful of Data provided Note: It also directly re-uses the client and transport. If you modify the Timeout, or RedirectPolicy on a clone, the clone will have a new http.client. It is recommended that the base request set your timeout and redirect polices, and no modification of the client or transport happen after cloning. Note: DoNotClearHttpClient is forced to "true" after Clone

func (*HttpClient) CustomMethod added in v1.7.6

func (dhc *HttpClient) CustomMethod(method, targetUrl string) *HttpClient

Just a wrapper to initialize HttpClient instance by method string

func (*HttpClient) Delete added in v1.7.6

func (dhc *HttpClient) Delete(targetUrl string) *HttpClient

func (*HttpClient) End added in v1.7.6

func (dhc *HttpClient) End(callback ...func(response Response, body string, err error)) (Response, string, error)

End is the most important function that you need to call when ending the chain. The request won't proceed without calling it. End function returns Response which matchs the structure of Response type in Golang'dhc http package (but without Body data). The body data itself returns as a string in a 2nd return value. Lastly but worth noticing, error array (NOTE: not just single error value) is returned as a 3rd value and nil otherwise.

For example:

resp, body, err := New().Get("http://www.baidu.com").End()
if err != nil {
  fmt.Println(err)
}
fmt.Println(resp, body)

Moreover, End function also supports callback which you can put as a parameter. This extends the flexibility and makes GoRequest fun and clean! You can use GoRequest in whatever style you love!

For example:

func printBody(resp Response, body string, errs []error){
  fmt.Println(resp.Status)
}
New().Get("http://www.baidu.com").End(printBody)

func (*HttpClient) EndBytes added in v1.7.6

func (dhc *HttpClient) EndBytes(callback ...func(response Response, body []byte, err error)) (Response, []byte, error)

EndBytes should be used when you want the body as bytes. The callbacks work the same way as with `End`, except that a byte array is used instead of a string.

func (*HttpClient) EndStruct added in v1.7.6

func (dhc *HttpClient) EndStruct(v interface{}, callback ...func(response Response, v interface{}, body []byte, err error)) (Response, []byte, error)

EndStruct should be used when you want the body as a struct. The callbacks work the same way as with `End`, except that a struct is used instead of a string.

func (*HttpClient) Get added in v1.7.6

func (dhc *HttpClient) Get(targetUrl string) *HttpClient

func (*HttpClient) Head added in v1.7.6

func (dhc *HttpClient) Head(targetUrl string) *HttpClient

func (*HttpClient) MakeRequest added in v1.7.6

func (dhc *HttpClient) MakeRequest() (*http.Request, error)

func (*HttpClient) Options added in v1.7.6

func (dhc *HttpClient) Options(targetUrl string) *HttpClient

func (*HttpClient) Param added in v1.7.6

func (dhc *HttpClient) Param(key string, value string) *HttpClient

As Go conventions accepts ; as a synonym for &. (https://github.com/golang/go/issues/2210) Thus, Query won't accept ; in a querystring if we provide something like fields=f1;f2;f3 This Param is then created as an alternative method to solve this.

func (*HttpClient) Patch added in v1.7.6

func (dhc *HttpClient) Patch(targetUrl string) *HttpClient

func (*HttpClient) Post added in v1.7.6

func (dhc *HttpClient) Post(targetUrl string) *HttpClient

func (*HttpClient) Proxy added in v1.7.6

func (dhc *HttpClient) Proxy(proxyUrl string) *HttpClient

Proxy function accepts a proxy url string to setup proxy url for any request. It provides a convenience way to setup proxy which have advantages over usual old ways. One example is you might try to set `http_proxy` environment. This means you are setting proxy up for all the requests. You will not be able to send different request with different proxy unless you change your `http_proxy` environment again. Another example is using Golang proxy setting. This is normal prefer way to do but too verbase compared to GoRequest'dhc Proxy:

New().Proxy("http://myproxy:9999").
  Post("http://www.google.com").
  End()

To set no_proxy, just put empty string to Proxy func:

New().Proxy("").
  Post("http://www.google.com").
  End()

func (*HttpClient) Put added in v1.7.6

func (dhc *HttpClient) Put(targetUrl string) *HttpClient

func (*HttpClient) Query added in v1.7.6

func (dhc *HttpClient) Query(content interface{}) *HttpClient

Query function accepts either json string or strings which will form a query-string in url of GET method or body of POST method. For example, making "/search?query=bicycle&size=50x50&weight=20kg" using GET method:

New().
  Get("/search").
  Query(`{ query: 'bicycle' }`).
  Query(`{ size: '50x50' }`).
  Query(`{ weight: '20kg' }`).
  End()

Or you can put multiple json values:

New().
  Get("/search").
  Query(`{ query: 'bicycle', size: '50x50', weight: '20kg' }`).
  End()

Strings are also acceptable:

New().
  Get("/search").
  Query("query=bicycle&size=50x50").
  Query("weight=20kg").
  End()

Or even Mixed! :)

New().
  Get("/search").
  Query("query=bicycle").
  Query(`{ size: '50x50', weight:'20kg' }`).
  End()

func (*HttpClient) RedirectPolicy added in v1.7.6

func (dhc *HttpClient) RedirectPolicy(policy func(req Request, via []Request) error) *HttpClient

RedirectPolicy accepts a function to define how to handle redirects. If the policy function returns an error, the next Request is not made and the previous request is returned.

The policy function'dhc arguments are the Request about to be made and the past requests in order of oldest first.

func (*HttpClient) Retry added in v1.7.6

func (dhc *HttpClient) Retry(retryCount int, retryTime time.Duration, statusCode ...int) *HttpClient

New().

Post("/gamelist").
Retry(3, 5 * time.seconds, http.StatusBadRequest, http.StatusInternalServerError).
End()

func (*HttpClient) Send added in v1.7.6

func (dhc *HttpClient) Send(content interface{}) *HttpClient

Send function accepts either json string or query strings which is usually used to assign data to POST or PUT method. Without specifying any type, if you give Send with json data, you are doing requesting in json format:

New().
  Post("/search").
  Send(`{ query: 'sushi' }`).
  End()

While if you use at least one of querystring, GoRequest understands and automatically set the Content-Type to `application/x-www-form-urlencoded`

New().
  Post("/search").
  Send("query=tonkatsu").
  End()

So, if you want to strictly send json format, you need to use Type func to set it as `json` (Please see more details in Type function). You can also do multiple chain of Send:

New().
  Post("/search").
  Send("query=bicycle&size=50x50").
  Send(`{ wheel: '4'}`).
  End()

From v0.2.0, Send function provide another convenience way to work with Struct type. You can mix and match it with json and query string:

type BrowserVersionSupport struct {
  Chrome string
  Firefox string
}
ver := BrowserVersionSupport{ Chrome: "37.0.2041.6", Firefox: "30.0" }
New().
  Post("/update_version").
  Send(ver).
  Send(`{"Safari":"5.1.10"}`).
  End()

If you have set Type to text or Content-Type to text/plain, content will be sent as raw string in body instead of form

New().
  Post("/greet").
  Type("text").
  Send("hello world").
  End()

func (*HttpClient) SendFile added in v1.7.6

func (dhc *HttpClient) SendFile(file interface{}, args ...string) *HttpClient

SendFile function works only with type "multipart". The function accepts one mandatory and up to two optional arguments. The mandatory (first) argument is the file. The function accepts a path to a file as string:

New().
  Post("http://example.com").
  Type("multipart").
  SendFile("./example_file.ext").
  End()

File can also be a []byte slice of a already file read by eg. ioutil.ReadFile:

b, _ := ioutil.ReadFile("./example_file.ext")
New().
  Post("http://example.com").
  Type("multipart").
  SendFile(b).
  End()

Furthermore file can also be a os.File:

f, _ := os.Open("./example_file.ext")
New().
  Post("http://example.com").
  Type("multipart").
  SendFile(f).
  End()

The first optional argument (second argument overall) is the filename, which will be automatically determined when file is a string (path) or a os.File. When file is a []byte slice, filename defaults to "filename". In all cases the automatically determined filename can be overwritten:

b, _ := ioutil.ReadFile("./example_file.ext")
New().
  Post("http://example.com").
  Type("multipart").
  SendFile(b, "my_custom_filename").
  End()

The second optional argument (third argument overall) is the fieldname in the multipart/form-data request. It defaults to fileNUMBER (eg. file1), where number is ascending and starts counting at 1. So if you send multiple files, the fieldnames will be file1, file2, ... unless it is overwritten. If fieldname is set to "file" it will be automatically set to fileNUMBER, where number is the greatest exsiting number+1.

b, _ := ioutil.ReadFile("./example_file.ext")
New().
  Post("http://example.com").
  Type("multipart").
  SendFile(b, "", "my_custom_fieldname"). // filename left blank, will become "example_file.ext"
  End()

func (*HttpClient) SendMap added in v1.7.6

func (dhc *HttpClient) SendMap(content interface{}) *HttpClient

func (*HttpClient) SendSlice added in v1.7.6

func (dhc *HttpClient) SendSlice(content []interface{}) *HttpClient

SendSlice (similar to SendString) returns HttpClient'dhc itself for any next chain and takes content []interface{} as a parameter. Its duty is to append slice of interface{} into dhc.SliceData ([]interface{}) which later changes into json array in the End() func.

func (*HttpClient) SendString added in v1.7.6

func (dhc *HttpClient) SendString(content string) *HttpClient

SendString returns HttpClient'dhc itself for any next chain and takes content string as a parameter. Its duty is to transform String into dhc.Data (map[string]interface{}) which later changes into appropriate format such as json, form, text, etc. in the End func. Send implicitly uses SendString and you should use Send instead of this.

func (*HttpClient) SendStruct added in v1.7.6

func (dhc *HttpClient) SendStruct(content interface{}) *HttpClient

SendStruct (similar to SendString) returns HttpClient'dhc itself for any next chain and takes content interface{} as a parameter. Its duty is to transfrom interface{} (implicitly always a struct) into dhc.Data (map[string]interface{}) which later changes into appropriate format such as json, form, text, etc. in the End() func.

func (*HttpClient) SetBasicAuth added in v1.7.6

func (dhc *HttpClient) SetBasicAuth(username string, password string) *HttpClient

SetBasicAuth sets the basic authentication header Example. To set the header for username "myuser" and password "mypass"

New()
  Post("/gamelist").
  SetBasicAuth("myuser", "mypass").
  End()

func (*HttpClient) SetCurlCommand added in v1.7.6

func (dhc *HttpClient) SetCurlCommand(enable bool) *HttpClient

Enable the curl command mode which display a CURL command line

func (*HttpClient) SetDebug added in v1.7.6

func (dhc *HttpClient) SetDebug(enable bool) *HttpClient

Enable the debug mode which logs request/response detail

func (*HttpClient) SetDoNotClearHttpClient added in v1.7.6

func (dhc *HttpClient) SetDoNotClearHttpClient(enable bool) *HttpClient

Enable the DoNotClear mode for not clearing super agent and reuse for the next request

func (*HttpClient) SetHeader added in v1.7.6

func (dhc *HttpClient) SetHeader(param string, value string) *HttpClient

Set is used for setting header fields, this will overwrite the existed values of Header through AppendHeader(). Example. To set `Accept` as `application/json`

New().
  Post("/gamelist").
  SetHeader("Accept", "application/json").
  End()

func (*HttpClient) SetHeaders added in v1.7.6

func (dhc *HttpClient) SetHeaders(headers interface{}) *HttpClient

SetHeaders is used to set headers with multiple fields. it accepts structs or json strings: for example:

New().Get(ts.URL).
SetHeaders(`{'Content-Type' = 'text/plain','X-Test-Tag'='test'}`).
End()

or

headers := struct {
    ContentType string `json:"Content-Type"`
    XTestTag string `json:"X-Test-Tag"`
} {ContentType:"text/plain",XTestTag:"test"}

New().Get(ts.URL).
SetHeaders(headers).
End()

func (*HttpClient) TLSClientConfig added in v1.7.6

func (dhc *HttpClient) TLSClientConfig(config *tls.Config) *HttpClient

Set TLSClientConfig for underling Transport. One example is you can use it to disable security check (https):

New().TLSClientConfig(&tls.Config{ InsecureSkipVerify: true}).
  Get("https://disable-security-check.com").
  End()

func (*HttpClient) Timeout

func (dhc *HttpClient) Timeout(timeout time.Duration) *HttpClient

http timeout

func (*HttpClient) Type added in v1.7.6

func (dhc *HttpClient) Type(typeStr string) *HttpClient

Type is a convenience function to specify the data type to send. For example, to send data as `application/x-www-form-urlencoded` :

New().
  Post("/recipe").
  Type("form").
  Send(`{ "name": "egg benedict", "category": "brunch" }`).
  End()

This will POST the body "name=egg benedict&category=brunch" to url /recipe

GoRequest supports

"text/html" uses "html"
"application/json" uses "json"
"application/xml" uses "xml"
"text/plain" uses "text"
"application/x-www-form-urlencoded" uses "urlencoded", "form" or "form-data"

type HttpClientRetryable added in v1.7.6

type HttpClientRetryable struct {
	RetryableStatus []int
	RetryTime       time.Duration
	RetryCount      int
	Attempt         int
	Enable          bool
}

type HttpServer

type HttpServer struct {
	GinLog                    bool           `inject:"httpServerGinLog" canNil:"true"`
	UseHttps                  bool           `inject:"httpServerUseHttps" canNil:"true"`
	HttpsCertFile             string         `inject:"httpServerHttpsCertFile" canNil:"true"`
	HttpsKeyFile              string         `inject:"httpServerHttpsKeyFile" canNil:"true"`
	HttpServerShutdownTimeout int64          `inject:"httpServerShutdownTimeout" canNil:"true"`
	HttpServerReadTimeout     int64          `inject:"httpServerReadTimeout" canNil:"true"`
	HttpServerWriteTimeout    int64          `inject:"httpServerWriteTimeout" canNil:"true"`
	HttpServerRunAddr         string         `inject:"httpServerRunAddr" canNil:"true"`
	HttpServerRunPort         int            `inject:"httpServerRunPort"`
	HttpServerInit            HttpServerInit `inject:"httpServerInit"`

	HandlerMap map[string]interface{}
	// contains filtered or unexported fields
}

func (*HttpServer) CheckHandle added in v1.6.3

func (h *HttpServer) CheckHandle() error

func (*HttpServer) Close added in v1.7.2

func (h *HttpServer) Close()

func (*HttpServer) DELETE added in v1.6.3

func (h *HttpServer) DELETE(group *gin.RouterGroup, relativePath string, handler interface{})

func (*HttpServer) GET added in v1.6.3

func (h *HttpServer) GET(group *gin.RouterGroup, relativePath string, handler interface{})

func (*HttpServer) Handle added in v1.6.3

func (h *HttpServer) Handle(group *gin.RouterGroup, httpMethod, relativePath string, handler interface{})

For GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used.

func (*HttpServer) OPTIONS added in v1.6.3

func (h *HttpServer) OPTIONS(group *gin.RouterGroup, relativePath string, handler interface{})

func (*HttpServer) PATCH added in v1.6.3

func (h *HttpServer) PATCH(group *gin.RouterGroup, relativePath string, handler interface{})

func (*HttpServer) POST added in v1.6.3

func (h *HttpServer) POST(group *gin.RouterGroup, relativePath string, handler interface{})

func (*HttpServer) PUT added in v1.6.3

func (h *HttpServer) PUT(group *gin.RouterGroup, relativePath string, handler interface{})

func (*HttpServer) Start added in v1.7.2

func (h *HttpServer) Start() error

type HttpServerInit added in v1.7.2

type HttpServerInit func(g *gin.Engine) error

type Request added in v1.7.6

type Request *http.Request

type Response added in v1.7.6

type Response *http.Response

Jump to

Keyboard shortcuts

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