httpClientV2

package
v1.64.50 Latest Latest
Warning

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

Go to latest
Published: Feb 9, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

README

HttpClientV2 使用说明

  1. 初始化

    package main
    
    import (
    	`fmt`
    
    	`github.com/aid297/aid/httpClient/httpClientV2`
    )
    
    func main() {
    	hc := httpClientV2.APP.HTTPClient.New(httpClientV2.URL("https://www.baidu.com"))
    	if err := hc.Send().OK(); err != nil {
    		panic(err)
    	}
    
    	res := hc.ToBytes()
    	fmt.Println(string(res))
    
    	// 输出结果
    	// <!DOCTYPE html>
    	// <!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus=autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=https://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');
    	// </script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173号&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>
    }
    
  2. 其他参数

    package main
    
    import (
    	`log`
    	`net/http`
    
    	`github.com/aid297/aid/httpClient/httpClientV2`
    	`github.com/aid297/aid/time`
    )
    
    func main() {
    	var wrongs []error
    
    	hc := httpClientV2.APP.HTTPClient.New(
    		httpClientV2.URL("https://", "这里", "为了方便", "可以直接", "使用", "可变参数", "的方式", "传入", "URL"),
    		httpClientV2.Method(http.MethodPost), // 设置访问方式
    		httpClientV2.SetHeaderValues(map[string][]any{}). // 设置请求头(如果有同一个 key 则进行值覆盖)
    			ContentType(httpClientV2.ContentTypeJSON). // 设置 Content-Type
    			Authorization("username", "password", "Basic"), // 设置认证
    	)
    
    	// 在这里可以追加或覆盖一些新的配置项,比如:
    	hc.SetAttrs(
    		httpClientV2.SetHeaderValue(map[string]any{}). // 设置请求投(如果有同一个 key 则进行值追加)
    			Accept(httpClientV2.AcceptJSON), // 设置 Accept
    		httpClientV2.Method(http.MethodPut), // 这里可以覆盖之前的属性
    		httpClientV2.AutoCopy(true),         // 设置自动备份响应体。默认情况下响应体不会自动读取流,所以如果需要在 Send 之后再次读取响应体,就需要设置这个属性为 true,来自动备份响应体内容,以便后续再次读取。
    	)
    
    	// 设置请求体:JSON
    	jsonBody := httpClientV2.JSON(map[string]any{})
    	hc.SetAttrs(jsonBody)
    
    	// 设置 form 表单数据
    	formBody := httpClientV2.Form(map[string]any{})
    	hc.SetAttrs(formBody)
    
    	// 设置 form-data 表单数据
    	formData := httpClientV2.FormData(map[string]string{}, map[string]string{})
    	hc.SetAttrs(formData)
    
    	// 这是一个很有用地请求体,我们可以把用户的请求例如 gin.Context.Request.Body 直接传入这个请求体中
    	readerBody := httpClientV2.Reader(nil)
    	hc.SetAttrs(readerBody)
    
    	if err := hc.Send().OK(); err != nil {
    		panic(err)
    	}
    
    	res := hc.ToBytes() // 读取 []byte 响应体
    	hc.ToJSON(&res)     // 读取 JSON 响应体并解析成 map[string]any
    	hc.ToXML(&res)      // 读取 XML 响应体并解析成 map[string]any
    	hc.ToWriter(nil)    // 通常与 Reader 配合使用,我们可以直接将用户请求流转发出去,也可以将响应流直接写入用户请求的响应流中
    
    	hc, wrongs = hc.SendWithRetry(5, 10*time.Second, func(statusCode int, err error) bool {
    		return statusCode != http.StatusOK || err != nil // 假设 status code 不等于 200 或者发生了错误都需要重试
    	})
    	// wrongs: 在重试过程中产生的错误
    	if len(wrongs) > 0 {
    		for _, wrong := range wrongs {
    			log.Printf("错误:%v\n", wrong)
    		}
    	}
    }
    

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ContentTypeJSON               ContentType = "application/json"
	ContentTypeXML                ContentType = "application/xml"
	ContentTypeXWwwFormURLencoded ContentType = "application/x-www-form-urlencoded"
	ContentTypeFormData           ContentType = "form-data"
	ContentTypePlain              ContentType = "text/plain"
	ContentTypeHTML               ContentType = "text/html"
	ContentTypeCSS                ContentType = "text/css"
	ContentTypeJavascript         ContentType = "text/javascript"
	ContentTypeSteam              ContentType = "application/octet-stream"
	ContentTypes                              = map[ContentType]string{
		ContentTypeJSON:               "application/json",
		ContentTypeXML:                "application/xml",
		ContentTypeXWwwFormURLencoded: "application/x-www-form-urlencoded",
		ContentTypeFormData:           "form-data",
		ContentTypePlain:              "text/plain",
		ContentTypeHTML:               "text/html",
		ContentTypeCSS:                "text/css",
		ContentTypeJavascript:         "text/javascript",
		ContentTypeSteam:              "application/octet-stream",
	}

	AcceptJSON       Accept = "application/json"
	AcceptXML        Accept = "application/xml"
	AcceptPlain      Accept = "text/plain"
	AcceptHTML       Accept = "text/html"
	AcceptCSS        Accept = "text/css"
	AcceptJavascript Accept = "text/javascript"
	AcceptSteam      Accept = "application/octet-stream"
	AcceptAny        Accept = "*/*"

	Accepts = map[Accept]string{
		AcceptJSON:       "application/json",
		AcceptXML:        "application/xml",
		AcceptPlain:      "text/plain",
		AcceptHTML:       "text/html",
		AcceptCSS:        "text/css",
		AcceptJavascript: "text/javascript",
		AcceptSteam:      "application/octet-stream",
		AcceptAny:        "*/*",
	}
)
View Source
var APP struct {
	HTTPClient        HTTPClient
	HTTPClientBuilder HTTPClientBuilder
}

Functions

This section is empty.

Types

type Accept

type Accept string

type AttrAppendHeaderValue

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

func AppendHeaderValue

func AppendHeaderValue(headers map[string]any) *AttrAppendHeaderValue

func (*AttrAppendHeaderValue) Accept

func (*AttrAppendHeaderValue) Append

func (my *AttrAppendHeaderValue) Append(headers map[string]any) *AttrAppendHeaderValue

func (*AttrAppendHeaderValue) AppendOne

func (my *AttrAppendHeaderValue) AppendOne(key string, value any) *AttrAppendHeaderValue

func (*AttrAppendHeaderValue) Authorization

func (my *AttrAppendHeaderValue) Authorization(username, password, title string) *AttrAppendHeaderValue

func (*AttrAppendHeaderValue) ContentType

func (my *AttrAppendHeaderValue) ContentType(contentType ContentType) *AttrAppendHeaderValue

func (*AttrAppendHeaderValue) Error

func (my *AttrAppendHeaderValue) Error() error

func (*AttrAppendHeaderValue) ImplHTTPClientAttributer

func (*AttrAppendHeaderValue) ImplHTTPClientAttributer()

func (*AttrAppendHeaderValue) Register

func (my *AttrAppendHeaderValue) Register(req *HTTPClient)

type AttrAppendHeaderValues

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

func AppendHeaderValues

func AppendHeaderValues(headers map[string][]any) *AttrAppendHeaderValues

func (*AttrAppendHeaderValues) Accept

func (*AttrAppendHeaderValues) Append

func (my *AttrAppendHeaderValues) Append(headers map[string][]any) *AttrAppendHeaderValues

func (*AttrAppendHeaderValues) AppendOne

func (my *AttrAppendHeaderValues) AppendOne(key string, values ...any) *AttrAppendHeaderValues

func (*AttrAppendHeaderValues) Authorization

func (my *AttrAppendHeaderValues) Authorization(username, password, title string) *AttrAppendHeaderValues

func (*AttrAppendHeaderValues) ContentType

func (my *AttrAppendHeaderValues) ContentType(contentType ContentType) *AttrAppendHeaderValues

func (*AttrAppendHeaderValues) Error

func (my *AttrAppendHeaderValues) Error() error

func (*AttrAppendHeaderValues) ImplHTTPClientAttributer

func (*AttrAppendHeaderValues) ImplHTTPClientAttributer()

func (*AttrAppendHeaderValues) Register

func (my *AttrAppendHeaderValues) Register(req *HTTPClient)

type AttrAutoCopyResBody

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

func AutoCopy

func AutoCopy(autoCopy bool) *AttrAutoCopyResBody

func (*AttrAutoCopyResBody) Error

func (*AttrAutoCopyResBody) Error() error

func (*AttrAutoCopyResBody) ImplHTTPClientAttributer

func (*AttrAutoCopyResBody) ImplHTTPClientAttributer()

func (*AttrAutoCopyResBody) Register

func (my *AttrAutoCopyResBody) Register(req *HTTPClient)

type AttrBody

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

func Bytes

func Bytes(body []byte) *AttrBody

func CSS

func CSS(body string) *AttrBody

func File

func File(filename string) *AttrBody

func Form

func Form(body map[string]any) *AttrBody

func FormData

func FormData(fields, files map[string]string) *AttrBody

func HTML

func HTML(body string) *AttrBody

func JSON

func JSON(body any) *AttrBody

func Javascript

func Javascript(body string) *AttrBody

func Plain

func Plain(body string) *AttrBody

func Reader

func Reader(body io.ReadCloser) *AttrBody

func (*AttrBody) Error

func (my *AttrBody) Error() error

func (*AttrBody) ImplHTTPClientAttributer

func (*AttrBody) ImplHTTPClientAttributer()

func (*AttrBody) Register

func (my *AttrBody) Register(req *HTTPClient)

type AttrCert

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

func Cert

func Cert(cert []byte) *AttrCert

func (*AttrCert) Error

func (my *AttrCert) Error() error

func (*AttrCert) ImplHTTPClientAttributer

func (*AttrCert) ImplHTTPClientAttributer()

func (*AttrCert) Register

func (my *AttrCert) Register(req *HTTPClient)

type AttrMethod

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

func Method

func Method(method string) *AttrMethod

func (*AttrMethod) Error

func (my *AttrMethod) Error() error

func (*AttrMethod) ImplHTTPClientAttributer

func (*AttrMethod) ImplHTTPClientAttributer()

func (*AttrMethod) Register

func (my *AttrMethod) Register(req *HTTPClient)

type AttrQueries

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

func Queries

func Queries(queries map[string]any) *AttrQueries

func (*AttrQueries) Append

func (my *AttrQueries) Append(queries map[string]any) *AttrQueries

func (*AttrQueries) AppendOne

func (my *AttrQueries) AppendOne(key string, value any) *AttrQueries

func (*AttrQueries) Error

func (my *AttrQueries) Error() error

func (*AttrQueries) ImplHTTPClientAttributer

func (*AttrQueries) ImplHTTPClientAttributer()

func (*AttrQueries) Register

func (my *AttrQueries) Register(req *HTTPClient)

func (*AttrQueries) RemoveEmpty added in v1.54.9

func (my *AttrQueries) RemoveEmpty() *AttrQueries

type AttrSetHeaderValue

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

func SetHeaderValue

func SetHeaderValue(headers map[string]any) *AttrSetHeaderValue

func (*AttrSetHeaderValue) Accept

func (my *AttrSetHeaderValue) Accept(accept Accept) *AttrSetHeaderValue

func (*AttrSetHeaderValue) Authorization

func (my *AttrSetHeaderValue) Authorization(username, password, title string) *AttrSetHeaderValue

func (*AttrSetHeaderValue) ContentType

func (my *AttrSetHeaderValue) ContentType(contentType ContentType) *AttrSetHeaderValue

func (*AttrSetHeaderValue) Error

func (my *AttrSetHeaderValue) Error() error

func (*AttrSetHeaderValue) ImplHTTPClientAttributer

func (*AttrSetHeaderValue) ImplHTTPClientAttributer()

func (*AttrSetHeaderValue) Register

func (my *AttrSetHeaderValue) Register(req *HTTPClient)

type AttrSetHeaderValues

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

func SetHeaderValues

func SetHeaderValues(headers map[string][]any) *AttrSetHeaderValues

func (*AttrSetHeaderValues) Accept

func (my *AttrSetHeaderValues) Accept(accept Accept) *AttrSetHeaderValues

func (*AttrSetHeaderValues) Authorization

func (my *AttrSetHeaderValues) Authorization(username, password, title string) *AttrSetHeaderValues

func (*AttrSetHeaderValues) ContentType

func (my *AttrSetHeaderValues) ContentType(contentType ContentType) *AttrSetHeaderValues

func (*AttrSetHeaderValues) Error

func (my *AttrSetHeaderValues) Error() error

func (*AttrSetHeaderValues) ImplHTTPClientAttributer

func (*AttrSetHeaderValues) ImplHTTPClientAttributer()

func (*AttrSetHeaderValues) Register

func (my *AttrSetHeaderValues) Register(req *HTTPClient)

type AttrTimeout

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

func Timeout

func Timeout(timeout time.Duration) *AttrTimeout

func (*AttrTimeout) Error

func (*AttrTimeout) Error() error

func (*AttrTimeout) ImplHTTPClientAttributer

func (*AttrTimeout) ImplHTTPClientAttributer()

func (*AttrTimeout) Register

func (my *AttrTimeout) Register(req *HTTPClient)

type AttrTransport

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

func Transport

func Transport(transport *http.Transport) *AttrTransport

func TransportDefault

func TransportDefault() *AttrTransport

func (*AttrTransport) Error

func (my *AttrTransport) Error() error

func (*AttrTransport) ImplHTTPClientAttributer

func (*AttrTransport) ImplHTTPClientAttributer()

func (*AttrTransport) Register

func (my *AttrTransport) Register(req *HTTPClient)

type AttrTransportDefault

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

type AttrURL

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

func (*AttrURL) Error

func (my *AttrURL) Error() error

func (*AttrURL) ImplHTTPClientAttributer

func (*AttrURL) ImplHTTPClientAttributer()

func (*AttrURL) Register

func (my *AttrURL) Register(req *HTTPClient)

type ContentType

type ContentType = string

type HTTPClient

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

func (*HTTPClient) DELETE

func (*HTTPClient) DELETE(attrs ...HTTPClientAttributer) *HTTPClient

func (*HTTPClient) Error

func (my *HTTPClient) Error() error

func (*HTTPClient) GET

func (*HTTPClient) GET(attrs ...HTTPClientAttributer) *HTTPClient

func (*HTTPClient) GetBody

func (my *HTTPClient) GetBody() []byte

func (*HTTPClient) GetCert

func (my *HTTPClient) GetCert() []byte

func (*HTTPClient) GetClient

func (my *HTTPClient) GetClient() *http.Client

func (*HTTPClient) GetHeaders

func (my *HTTPClient) GetHeaders() map[string][]any

func (*HTTPClient) GetMethod

func (my *HTTPClient) GetMethod() string

func (*HTTPClient) GetQueries

func (my *HTTPClient) GetQueries() map[string]any

func (*HTTPClient) GetRawRequest

func (my *HTTPClient) GetRawRequest() *http.Request

func (*HTTPClient) GetRawResponse

func (my *HTTPClient) GetRawResponse() *http.Response

func (*HTTPClient) GetStatus added in v1.51.21

func (my *HTTPClient) GetStatus() string

func (*HTTPClient) GetStatusCode added in v1.51.21

func (my *HTTPClient) GetStatusCode() int

func (*HTTPClient) GetTimeout

func (my *HTTPClient) GetTimeout() time.Duration

func (*HTTPClient) GetTransport

func (my *HTTPClient) GetTransport() *http.Transport

func (*HTTPClient) GetURL

func (my *HTTPClient) GetURL() string

func (*HTTPClient) HEAD

func (*HTTPClient) HEAD(attrs ...HTTPClientAttributer) *HTTPClient

func (*HTTPClient) New

func (*HTTPClient) New(attrs ...HTTPClientAttributer) *HTTPClient

func (*HTTPClient) OK added in v1.57.3

func (my *HTTPClient) OK() error

OK 检查响应是否成功,返回布尔值和错误信息

func (*HTTPClient) OPTIONS

func (*HTTPClient) OPTIONS(attrs ...HTTPClientAttributer) *HTTPClient

func (*HTTPClient) PATCH

func (*HTTPClient) PATCH(attrs ...HTTPClientAttributer) *HTTPClient

func (*HTTPClient) POST

func (*HTTPClient) POST(attrs ...HTTPClientAttributer) *HTTPClient

func (*HTTPClient) PUT

func (*HTTPClient) PUT(attrs ...HTTPClientAttributer) *HTTPClient

func (*HTTPClient) Send

func (my *HTTPClient) Send() *HTTPClient

func (*HTTPClient) SendWithRetry

func (my *HTTPClient) SendWithRetry(count uint, interval time.Duration, condition func(statusCode int, err error) bool) (*HTTPClient, []error)

func (*HTTPClient) SetAttrs

func (my *HTTPClient) SetAttrs(attrs ...HTTPClientAttributer) *HTTPClient

func (*HTTPClient) TRACE

func (*HTTPClient) TRACE(attrs ...HTTPClientAttributer) *HTTPClient

func (*HTTPClient) ToBytes

func (my *HTTPClient) ToBytes() []byte

func (*HTTPClient) ToJSON

func (my *HTTPClient) ToJSON(target any, keys ...any) *HTTPClient

func (*HTTPClient) ToWriter

func (my *HTTPClient) ToWriter(writer http.ResponseWriter) *HTTPClient

func (*HTTPClient) ToXML

func (my *HTTPClient) ToXML(target any) *HTTPClient

type HTTPClientAttributer

type HTTPClientAttributer interface {
	Register(req *HTTPClient)
	Error() error
	ImplHTTPClientAttributer()
}

func URL

func URL(urls ...any) HTTPClientAttributer

func XML

func XML(body any) HTTPClientAttributer

type HTTPClientBuilder

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

func (*HTTPClientBuilder) GetClient

func (my *HTTPClientBuilder) GetClient() *HTTPClient

func (*HTTPClientBuilder) New

Jump to

Keyboard shortcuts

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