builder

package module
v0.4.6 Latest Latest
Warning

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

Go to latest
Published: Dec 20, 2023 License: MIT Imports: 27 Imported by: 3

README

Here is a generated GitHub README.md based on the provided Go code:

Go HTTP Client Builder

Go HTTP Client Builder is a Go package for building HTTP clients with fluent interface. It provides an easy way to configure HTTP requests and handle responses.

Installation

go get github.com/catnovel/builder

Usage

Create a new client
client := builder.NewClient()
Configure the client
client.SetBaseUrl("https://api.example.com")
       .SetTimeout(30)
       .SetUserAgent("my-app/1.0")
Make a request
req := client.R()
resp, err := req.Get("/users")
Handle response
if err != nil {
  // handle error
}

fmt.Println(resp.GetStatusCode())
fmt.Println(resp.String())
Post form data
req.SetFormData(map[string]string{
  "name": "John",
  "email": "john@email.com", 
})

resp, err := req.Post("/users")

Request builder

The R() method creates a new Request object that can be used to configure an HTTP request.

Set request body
req.SetBody(map[string]interface{}{
  "name": "John",
  "age": 30,
})

Supports body types: string, []byte, map[string]interface{}, etc.

Set request headers
req.SetHeader("Content-Type", "application/json")
   .SetHeader("Authorization", "Bearer token")
Set query parameters
req.SetQueryParam("sort", "desc")
   .SetQueryParam("limit", 100)
Set cookies
req.SetCookies([]*http.Cookie{
  {Name: "session", Value: "1234"},
})

Response builder

The Response object contains the HTTP response and useful methods to handle it.

Get response as string
resp.String()
Get response as JSON
var data struct{}
resp.Json(&data) 
Get response as HTML document
doc := resp.Html()
Get response headers
headers := resp.GetHeader()

Full Example

client := builder.NewClient()
req := client.R()

req.SetQueryParam("page", 1)
   .SetHeader("Authorization", "token")

resp, err := req.Get("/users")

if err != nil {
  // handle error 
}

var result []User
resp.Json(&result)

Contributing

Pull requests are welcome. Feel free to open an issue for any bugs or feature requests.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	// MethodGet HTTP method
	MethodGet = "GET"

	// MethodPost HTTP method
	MethodPost = "POST"

	// MethodPut HTTP method
	MethodPut = "PUT"

	// MethodDelete HTTP method
	MethodDelete = "DELETE"

	// MethodPatch HTTP method
	MethodPatch = "PATCH"

	// MethodHead HTTP method
	MethodHead = "HEAD"

	// MethodOptions HTTP method
	MethodOptions = "OPTIONS"
)

Variables

This section is empty.

Functions

func DetectContentType added in v0.3.1

func DetectContentType(body interface{}) string

DetectContentType method is used to figure out `Request.Body` content type for request header

func IsJSONType added in v0.3.1

func IsJSONType(ct string) bool

IsJSONType method is to check JSON content type or not

func IsStringEmpty added in v0.3.1

func IsStringEmpty(str string) bool

IsStringEmpty method tells whether given string is empty or not

func IsXMLType added in v0.3.1

func IsXMLType(ct string) bool

IsXMLType method is to check XML content type or not

Types

type Client

type Client struct {
	sync.RWMutex                // 用于保证线程安全
	MaxConcurrent chan struct{} // 用于限制并发数

	Header     map[string]string // Header 用于存储 HTTP 请求的 Header 部分
	QueryParam map[string]string // QueryParam 用于存储 HTTP 请求的 Query 部分

	FormData               map[string]string
	Token                  string
	AuthScheme             string
	Cookies                []*http.Cookie
	Debug                  bool
	AllowGetMethodPayload  bool
	RetryCount             int
	JSONMarshal            func(v interface{}) ([]byte, error)
	JSONUnmarshal          func(data []byte, v interface{}) error
	XMLMarshal             func(v interface{}) ([]byte, error)
	XMLUnmarshal           func(data []byte, v interface{}) error
	HeaderAuthorizationKey string
	// contains filtered or unexported fields
}

Client 类型用于存储 HTTP 请求的相关信息。

func NewClient

func NewClient() *Client

NewClient 方法用于创建一个新的 Client 对象, 并返回该对象的指针。

func (*Client) GetClientBaseURL added in v0.0.8

func (client *Client) GetClientBaseURL() string

GetClientBaseURL 方法用于获取 HTTP 请求的 BaseUrl 部分。它返回一个 string 类型的参数。

func (*Client) GetClientBody

func (client *Client) GetClientBody() interface{}

GetClientBody 方法用于获取 HTTP 请求的 Body 部分。它返回一个 interface{} 类型的参数。

func (*Client) GetClientCookie

func (client *Client) GetClientCookie() string

GetClientCookie 方法用于获取 HTTP 请求的 Cookie 部分。它返回一个 string 类型的参数。

func (*Client) GetClientDebug

func (client *Client) GetClientDebug() bool

GetClientDebug 方法用于获取 HTTP 请求的 Debug 部分。它返回一个 bool 类型的参数。

func (*Client) GetClientQueryParams

func (client *Client) GetClientQueryParams() map[string]string

GetClientQueryParams 方法用于获取 HTTP 请求的 Query 部分。它返回一个

func (*Client) GetClientRetryNumber

func (client *Client) GetClientRetryNumber() int

GetClientRetryNumber 方法用于获取 HTTP 请求的 RetryNumber 部分。它返回一个 int 类型的参数。

func (*Client) GetClientTimeout

func (client *Client) GetClientTimeout() int

GetClientTimeout 方法用于获取 HTTP 请求的 Timeout 部分。它返回一个 int 类型的参数。

func (*Client) LogDebug added in v0.4.1

func (client *Client) LogDebug(info string)

func (*Client) LogError added in v0.4.1

func (client *Client) LogError(err any, query any, fileName, funcName string)

func (*Client) LogFatal added in v0.4.1

func (client *Client) LogFatal(err error, query any, fileName string, funcName string)

func (*Client) LogInfo added in v0.4.1

func (client *Client) LogInfo(err any, query any, funcName string)

func (*Client) R

func (client *Client) R() *Request

R 方法用于创建一个新的 Request 对象。它接收一个 string 类型的参数,该参数表示 HTTP 请求的 Path 部分。

func (*Client) SetAuthorizationKey added in v0.3.1

func (client *Client) SetAuthorizationKey(authToken string) *Client

SetAuthorizationKey 方法用于设置 HTTP 请求的 Authorization 部分。它接收一个 string 类型的参数,该参数表示 Authorization 的值。

func (*Client) SetBaseURL

func (client *Client) SetBaseURL(baseUrl string) *Client

SetBaseURL 方法用于设置HTTP请求的 BaseUrl 部分。它接收一个 string 类型的参数,该参数表示 BaseUrl 的值。

func (*Client) SetBasicAuth

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

SetBasicAuth 方法用于设置 HTTP 请求的 BasicAuth 部分。它接收两个 string 类型的参数,分别表示用户名和密码。

func (*Client) SetContentType added in v0.1.0

func (client *Client) SetContentType(contentType string) *Client

SetContentType 方法用于设置 HTTP 请求的 ContentType 部分。它接收一个 string 类型的参数,该参数表示 ContentType 的值。

func (*Client) SetCookie

func (client *Client) SetCookie(cookie *http.Cookie) *Client

func (*Client) SetCookieJar

func (client *Client) SetCookieJar(cookieJar http.CookieJar) *Client

SetCookieJar 方法用于设置 HTTP 请求的 CookieJar 部分。它接收一个 http.CookieJar 类型的参数,该参数表示 CookieJar 的值。

func (*Client) SetCookieString added in v0.4.5

func (client *Client) SetCookieString(cookieStr string) *Client

SetCookieString 方法用于设置 HTTP 请求的 Cookie 部分。它接收一个 string 类型的参数,该参数表示 Cookie 的值。

func (*Client) SetCookies added in v0.4.5

func (client *Client) SetCookies(cookie []*http.Cookie) *Client

func (*Client) SetDebug

func (client *Client) SetDebug() *Client

SetDebug 方法用于设置是否输出调试信息,如果调用该方法,那么将输出调试信息。

func (*Client) SetDebugFile

func (client *Client) SetDebugFile(name string) *Client

SetDebugFile 方法用于设置输出调试信息的文件。它接收一个 string 类型的参数,该参数表示文件名。

func (*Client) SetFormData added in v0.3.1

func (client *Client) SetFormData(key string, value string) *Client

func (*Client) SetFormDataMany added in v0.3.1

func (client *Client) SetFormDataMany(params url.Values) *Client

SetFormDataMany 方法用于设置 HTTP 请求的 Query 部分。它接收一个 url.Values 类型的参数,

func (*Client) SetHeader

func (client *Client) SetHeader(key string, value interface{}) *Client

SetHeader 方法用于设置 HTTP 请求的 Header 部分。它接收两个 string 类型的参数,

func (*Client) SetHeaders

func (client *Client) SetHeaders(headers map[string]interface{}) *Client

SetHeaders 方法用于设置 HTTP 请求的 Header 部分。它接收一个 map[string]interface{} 类型的参数,

func (*Client) SetProxy

func (client *Client) SetProxy(proxy string) *Client

SetProxy 方法用于设置 HTTP 请求的 Proxy 部分。它接收一个 string 类型的参数,该参数表示 Proxy 的值。

func (*Client) SetQueryParam

func (client *Client) SetQueryParam(key string, value any) *Client

SetQueryParam 方法用于设置 HTTP 请求的 Query 部分。它接收两个 string 类型的参数,

func (*Client) SetQueryParamString

func (client *Client) SetQueryParamString(query string) *Client

SetQueryParamString 方法用于设置 HTTP 请求的 Query 部分。它接收一个 string 类型的参数,

func (*Client) SetQueryParams

func (client *Client) SetQueryParams(params map[string]any) *Client

SetQueryParams 方法用于设置 HTTP 请求的 Query 部分。它接收一个 map[string]interface{} 类型的参数,

func (*Client) SetResultFunc added in v0.1.0

func (client *Client) SetResultFunc(f func(v string) (string, error)) *Client

func (*Client) SetRetryCount added in v0.1.0

func (client *Client) SetRetryCount(count int) *Client

SetRetryCount 方法用于设置重试次数。它接收一个 int 类型的参数,该参数表示重试次数。

func (*Client) SetTimeout

func (client *Client) SetTimeout(timeout int) *Client

SetTimeout 方法用于设置 HTTP 请求的 Timeout 部分, timeout 单位为秒。它接收一个 int 类型的参数,该参数表示 Timeout 的值。

func (*Client) SetUserAgent

func (client *Client) SetUserAgent(userAgent string) *Client

SetUserAgent 方法用于设置 HTTP 请求的 User-Agent 部分。它接收一个 string 类型的参数,该参数表示 User-Agent 的值。

type Request

type Request struct {
	URL *url.URL

	Method string // HTTP 请求的 Method 部分
	Body   interface{}

	Header     sync.Map
	QueryParam sync.Map
	FormData   sync.Map
	Cookies    []*http.Cookie
	NewRequest *http.Request
	// contains filtered or unexported fields
}

func (*Request) Delete

func (request *Request) Delete(url string) (*Response, error)

Delete 方法用于创建一个 DELETE 请求。它接收一个 string 类型的参数,表示 HTTP 请求的路径。

func (*Request) Get

func (request *Request) Get(url string) (*Response, error)

Get 方法用于创建一个 GET 请求。它接收一个 string 类型的参数,表示 HTTP 请求的路径。

func (*Request) GetFormDataEncode added in v0.3.1

func (request *Request) GetFormDataEncode() string

GetFormDataEncode 方法用于获取 HTTP 请求的 Query 部分的 URL 编码字符串。

func (*Request) GetHeaderContentType added in v0.3.1

func (request *Request) GetHeaderContentType() string

func (*Request) GetHost

func (request *Request) GetHost() string

GetHost 方法用于获取 HTTP 请求的 Host 部分的字符串。

func (*Request) GetMethod

func (request *Request) GetMethod() string

GetMethod 方法用于获取 HTTP 请求的 Method 部分的字符串。

func (*Request) GetPath

func (request *Request) GetPath() string

GetPath 方法用于获取 HTTP 请求的 Path 部分的字符串。

func (*Request) GetQueryParamsEncode

func (request *Request) GetQueryParamsEncode() string

GetQueryParamsEncode 方法用于获取 HTTP 请求的 Query 部分的 URL 编码字符串。

func (*Request) GetQueryParamsNopCloser

func (request *Request) GetQueryParamsNopCloser() io.ReadCloser

GetQueryParamsNopCloser 方法用于获取 HTTP 请求的 Query 部分的 ReadCloser。

func (*Request) GetRequestHeader

func (request *Request) GetRequestHeader() http.Header

GetRequestHeader 方法用于获取 HTTP 请求的 Header 部分的 http.Header。

func (*Request) GetUrl

func (request *Request) GetUrl() string

GetUrl 方法用于获取 HTTP 请求的 URL 部分的字符串。

func (*Request) Head

func (request *Request) Head(url string) (*Response, error)

Head 方法用于创建一个 HEAD 请求。它接收一个 string 类型的参数,表示 HTTP 请求的路径。

func (*Request) Options

func (request *Request) Options(url string) (*Response, error)

Options 方法用于创建一个 OPTIONS 请求。它接收一个 string 类型的参数,表示 HTTP 请求的路径。

func (*Request) Patch

func (request *Request) Patch(url string) (*Response, error)

Patch 方法用于创建一个 PATCH 请求。它接收一个 string 类型的参数,表示 HTTP 请求的路径。

func (*Request) Post

func (request *Request) Post(url string) (*Response, error)

Post 方法用于创建一个 POST 请求。它接收一个 string 类型的参数,表示 HTTP 请求的路径。

func (*Request) Put

func (request *Request) Put(url string) (*Response, error)

Put 方法用于创建一个 PUT 请求。它接收一个 string 类型的参数,表示 HTTP 请求的路径。

func (*Request) SetBody

func (request *Request) SetBody(v interface{}) *Request

func (*Request) SetCookie

func (request *Request) SetCookie(cookie *http.Cookie) *Request

SetCookie 方法用于设置 HTTP 请求的 Cookie 部分。它接收一个 *http.Cookie 类型的参数,

func (*Request) SetCookies

func (request *Request) SetCookies(cookie []*http.Cookie) *Request

SetCookies 方法用于设置 HTTP 请求的 Cookies 部分。它接收一个 []*http.Cookie 类型的参数,

func (*Request) SetFormData added in v0.3.1

func (request *Request) SetFormData(key string, value any) *Request

func (*Request) SetFormDataMany added in v0.3.1

func (request *Request) SetFormDataMany(params map[string]string) *Request

func (*Request) SetHeader

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

SetHeader 方法用于设置 HTTP 请求的 Header 部分。它接收两个 string 类型的参数,

func (*Request) SetHeaderContentType added in v0.3.1

func (request *Request) SetHeaderContentType(contentType string) *Request

func (*Request) SetHeaders added in v0.0.8

func (request *Request) SetHeaders(headers map[string]string) *Request

func (*Request) SetQueryParam

func (request *Request) SetQueryParam(key string, value interface{}) *Request

SetQueryParam 方法用于设置 HTTP 请求的 Query 部分。它接收两个 string 类型的参数,

func (*Request) SetQueryParams

func (request *Request) SetQueryParams(query map[string]string) *Request

SetQueryParams 方法用于设置 HTTP 请求的 Query 部分。它接收一个 map[string]interface{} 类型的参数,

func (*Request) SetQueryString

func (request *Request) SetQueryString(query string) *Request

SetQueryString 方法用于设置 HTTP 请求的 Query 部分。它接收一个 string 类型的参数,

type Response

type Response struct {
	Request       *http.Request
	Result        string         // 响应体字符串结果
	ResponseRaw   *http.Response // 指向 http.Response 的指针
	RequestSource *Request       // 指向 Request 的指针
}

func (*Response) GetByte

func (response *Response) GetByte() []byte

GetByte 方法用于获取 HTTP 响应的字节结果。

func (*Response) GetCookieString added in v0.4.5

func (response *Response) GetCookieString() string

func (*Response) GetCookies

func (response *Response) GetCookies() []*http.Cookie

GetCookies 方法用于获取 HTTP 响应的 Cookies 部分。

func (*Response) GetHeader

func (response *Response) GetHeader() http.Header

GetHeader 方法用于获取 HTTP 响应的 Header 部分。

func (*Response) GetProto added in v0.1.0

func (response *Response) GetProto() string

func (*Response) GetStatus

func (response *Response) GetStatus() string

GetStatus 方法用于获取 HTTP 响应的状态。

func (*Response) GetStatusCode

func (response *Response) GetStatusCode() int

GetStatusCode 方法用于获取 HTTP 响应的状态码。

func (*Response) Gjson

func (response *Response) Gjson() gjson.Result

Gjson 方法用于将 HTTP 响应的字符串结果解析为 gjson.Result 对象。

func (*Response) Html

func (response *Response) Html() *goquery.Document

Html 方法用于将 HTTP 响应的字符串结果解析为 HTML 文档。

func (*Response) HtmlGbk

func (response *Response) HtmlGbk() *goquery.Document

HtmlGbk 方法用于将 HTTP 响应的字符串结果解析为 GBK 编码的 HTML 文档。

func (*Response) IsStatusOk

func (response *Response) IsStatusOk() bool

func (*Response) Json

func (response *Response) Json(v any) error

Json 方法用于将 HTTP 响应的字符串结果解析为 JSON 对象。它接收一个 interface{} 类型的参数,该参数必须是指针类型。

func (*Response) String

func (response *Response) String() string

String 方法用于获取 HTTP 响应的字符串结果。

func (*Response) StringGbk

func (response *Response) StringGbk() string

StringGbk 方法用于将 HTTP 响应的字符串结果解码为 GBK 编码的字符串。

Directories

Path Synopsis
pkg

Jump to

Keyboard shortcuts

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