quicklyHttps

package module
v0.0.0-...-bc49cbf Latest Latest
Warning

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

Go to latest
Published: May 31, 2024 License: Apache-2.0 Imports: 22 Imported by: 0

README

QuicklyHttps

QuicklyHttps is a versatile and easy-to-use HTTP client library for Go that simplifies the process of making HTTP requests. It offers enhanced features such as logging, retry mechanism, and simplified API for common HTTP methods.

Introduction

QuicklyHttps addresses the common challenges developers face when working with HTTP requests in Go. The motivation behind creating QuicklyHttps was to provide an all-in-one solution that integrates useful functionalities like logging, retry logic, and easy-to-use interfaces for making HTTP requests. This library is designed to be both robust and flexible, allowing developers to handle HTTP communications effortlessly.

With QuicklyHttps, you can easily configure and send HTTP requests, handle responses, and manage cookies and headers. The library also supports JSON and form data submissions, making it an ideal choice for building RESTful APIs and web clients.

Key Features
  • Enhanced Logging: Integrated support for leveled logging to track request and response details.
  • Retry Mechanism: Configurable retry logic to handle transient network issues.
  • Easy Configuration: Simple methods to set up headers, query parameters, and form data.
  • JSON and Form Data Handling: Convenient methods to send and receive JSON and form data.
  • Proxy Support: Easily configure proxy settings for HTTP requests.
  • Debug Mode: Enable debug mode to log detailed request and response information.

Installation and Deployment

To install QuicklyHttps, you need to have Go installed on your machine. You can install QuicklyHttps using the following command:

go get github.com/catnovel/quicklyHttps

Next, import the package in your Go code:

import "github.com/catnovel/quicklyHttps"

Usage

Creating a Client and Making Requests

Here’s how you can create a client and make a simple GET request:

client := quicklyHttps.NewClient()
response, err := client.Get("https://api.example.com/data", nil, nil)
if err != nil {
    log.Fatal(err)
}
fmt.Println(response.String())
Setting Headers and Query Parameters

You can set headers and query parameters for your requests:

client := quicklyHttps.NewClient()
response, err := client.SetHeader("Authorization", "Bearer token").SetQueryParam("key", "value").Get("https://api.example.com/data", nil, nil)
if err != nil {
    log.Fatal(err)
}
fmt.Println(response.String())
Posting Form Data

To post form data, you can use the PostForm method:

formData := map[string]string{
    "username": "testuser",
    "password": "password123",
}
response, err := client.PostForm("https://api.example.com/login", formData, nil)
if err != nil {
    log.Fatal(err)
}
fmt.Println(response.String())
Posting JSON Data

For posting JSON data, use the PostJSON method:

jsonData := map[string]interface{}{
    "title": "New Post",
    "body": "This is the content of the new post.",
}
response, err := client.PostJSON("https://api.example.com/posts", jsonData, nil)
if err != nil {
    log.Fatal(err)
}
fmt.Println(response.String())

Running Tests

To run tests for QuicklyHttps, use the following command:

go test ./...

This command will run all the test cases and display the results. Ensure you have written comprehensive test cases to cover different scenarios and edge cases.

Dependencies

QuicklyHttps relies on the following dependencies:

  • golang.org/x/text/encoding/simplifiedchinese for encoding conversions.
  • github.com/tidwall/gjson for JSON parsing.

Ensure these dependencies are included in your go.mod file.

Development Status and Contributions

Currently, QuicklyHttps is in active development. We plan to add more features and improve the existing functionalities. Contributions are welcome! If you find any issues or want to contribute, please create a pull request or open an issue on GitHub.

Documentation

Index

Constants

View Source
const (
	ContentTypeJson      = "application/json"
	ContentTypeForm      = "application/x-www-form-urlencoded"
	ContentTypeXml       = "application/xml"
	ContentTypeStream    = "application/octet-stream"
	ContentTypeText      = "text/plain"
	ContentTypeHtml      = "text/html"
	ContentTypeMultipart = "multipart/form-data"
)

Variables

This section is empty.

Functions

func ConvertGBKToUTF8

func ConvertGBKToUTF8(gbkData []byte) ([]byte, error)

ConvertGBKToUTF8 将 GBK 编码的字节数组转换为 UTF-8 编码

func IsStringEmpty

func IsStringEmpty(str string) bool

IsStringEmpty method tells whether given string is empty or not

Types

type Client

type Client struct {
	*http.Client                             // HTTP 客户端
	BasicAuthToken         string            // 基本认证令牌
	HeaderAuthorizationKey string            // 认证头部键
	AuthScheme             string            // 认证方案
	Method                 string            // 请求方法
	BaseURL                string            // 请求的基础 URL
	Timeout                time.Duration     // 请求超时
	Logger                 LeveledLogger     // 日志记录器
	RetryMax               int               // 最大重试次数
	Cookies                []*http.Cookie    // 每个请求都要发送的 cookie
	Header                 http.Header       // 每个请求都要发送的头部
	QueryParams            map[string]string // 请求的查询参数
	Body                   string            // 请求的主体内容
	FormParams             urlpkg.Values     // 表单参数
	Debug                  bool              // 是否启用调试模式

	UserInfo *User // 用户信息, 用于请求认证
	// contains filtered or unexported fields
}

Client 用于发出 HTTP 请求,添加了额外的功能

func NewClient

func NewClient() *Client

NewClient 使用默认设置创建一个新的 Client

func (*Client) ClearCookies

func (c *Client) ClearCookies() *Client

func (*Client) Get

func (c *Client) Get(url string, params, headers map[string]string) (*Response, error)

Get is a convenience helper for doing simple GET requests.

func (*Client) GetCookies

func (c *Client) GetCookies(url string) ([]*http.Cookie, error)

GetCookies get cookies from the underlying `http.Client`'s `CookieJar`.

func (*Client) Head

func (c *Client) Head(url string, params, headers map[string]string) (*Response, error)

Head is a convenience method for doing simple HEAD requests.

func (*Client) Post

func (c *Client) Post(url string, params, headers map[string]string) (*Response, error)

func (*Client) PostForm

func (c *Client) PostForm(url string, data, headers map[string]string) (*Response, error)

PostForm is a convenience method for doing simple POST operations using pre-filled url.Values form data.

func (*Client) PostJSON

func (c *Client) PostJSON(url string, data any, headers map[string]string) (*Response, error)

PostJSON is a convenience method for doing simple POST operations using JSON data.

func (*Client) R

func (c *Client) R() *Request

func (*Client) SetAuthScheme

func (c *Client) SetAuthScheme(scheme string) *Client

func (*Client) SetBaseURL

func (c *Client) SetBaseURL(baseURL string) *Client

SetBaseURL 设置基础 URL

func (*Client) SetBasicAuth

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

func (*Client) SetBasicAuthToken

func (c *Client) SetBasicAuthToken(token string) *Client

func (*Client) SetBody

func (c *Client) SetBody(body string) *Client

SetBody 设置请求体

func (*Client) SetBodyJSON

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

SetBodyJSON 将请求体设置为 JSON 对象

func (*Client) SetCheckRedirect

func (c *Client) SetCheckRedirect(f func(req *http.Request, via []*http.Request) error) *Client

SetCheckRedirect 设置重定向函数

func (*Client) SetCookie

func (c *Client) SetCookie(cookies string) *Client

SetCookie 解析并设置 cookie 字符串

func (*Client) SetCookieRaw

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

SetCookieRaw 增加单个原始 cookie

func (*Client) SetCookiesRaw

func (c *Client) SetCookiesRaw(cookies []*http.Cookie) *Client

SetCookiesRaw 设置原始 cookie 切片

func (*Client) SetDebug

func (c *Client) SetDebug(debug bool) *Client

SetDebug 启用或禁用调试模式

func (*Client) SetFormParam

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

SetFormParam 设置单个表单参数

func (*Client) SetFormParams

func (c *Client) SetFormParams(params map[string]string) *Client

SetFormParams 设置多个表单参数

func (*Client) SetHandleRequestResultFunc

func (c *Client) SetHandleRequestResultFunc(f HandleRequestResult) *Client

func (*Client) SetHeader

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

SetHeader 设置单个请求头部

func (*Client) SetHeaders

func (c *Client) SetHeaders(headers map[string]string) *Client

SetHeaders 设置多个请求头部

func (*Client) SetMethod

func (c *Client) SetMethod(method string) *Client

SetMethod 设置请求方法

func (*Client) SetProxyURL

func (c *Client) SetProxyURL(proxy string) *Client

SetProxyURL 设置代理服务器 URL

func (*Client) SetQueryParam

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

SetQueryParam 设置单个查询参数

func (*Client) SetQueryParams

func (c *Client) SetQueryParams(params map[string]string) *Client

SetQueryParams 设置多个查询参数

func (*Client) SetRetryMax

func (c *Client) SetRetryMax(retryMax int) *Client

SetRetryMax 设置最大重试次数

func (*Client) SetTimeout

func (c *Client) SetTimeout(timeout time.Duration) *Client

SetTimeout 设置请求超时

func (*Client) SetUserAgent

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

SetUserAgent 设置 User-Agent 头

type HandleRequestResult

type HandleRequestResult func(rawRequest *http.Request) *http.Request

type HandleResponseResult

type HandleResponseResult func(rawRequest *Request, response *Response)

type LeveledLogger

type LeveledLogger interface {
	Error(msg string, keysAndValues ...interface{})
	Info(msg string, keysAndValues ...interface{})
	Debug(msg string, keysAndValues ...interface{})
	Warn(msg string, keysAndValues ...interface{})
	WithContext(ctx context.Context) LeveledLogger
}

LeveledLogger 接口定义了分级日志记录的方法

type Request

type Request struct {
	*http.Request

	GetBody func() (io.ReadCloser, error)

	Header http.Header
	// contains filtered or unexported fields
}

Request 封装了 HTTP 请求及其相关数据

func (*Request) AddHeader

func (r *Request) AddHeader(key, value string) *Request

AddHeader 添加请求头

func (*Request) DelHeader

func (r *Request) DelHeader(key string) *Request

DelHeader 删除请求头

func (*Request) DelQueryParam

func (r *Request) DelQueryParam(key string) *Request

DelQueryParam 删除查询参数

func (*Request) Do

func (r *Request) Do() (*Response, error)

func (*Request) Execute

func (r *Request) Execute(urlPath string) (*Response, error)

Execute 执行请求并返回响应

func (*Request) GetHeader

func (r *Request) GetHeader(key string) string

GetHeader 获取请求头

func (*Request) SetBody

func (r *Request) SetBody(body string) *Request

func (*Request) SetBodyBytes

func (r *Request) SetBodyBytes(body []byte) *Request

SetBodyBytes 设置请求体为字节数组

func (*Request) SetBodyJSON

func (r *Request) SetBodyJSON(data any) *Request

func (*Request) SetContext

func (r *Request) SetContext(ctx context.Context) *Request

func (*Request) SetCookie

func (r *Request) SetCookie(cookies string) *Request

SetCookie 设置 Cookie

func (*Request) SetCookieRaw

func (r *Request) SetCookieRaw(cookie *http.Cookie) *Request

SetCookieRaw 设置单个原始 Cookie

func (*Request) SetCookiesRaw

func (r *Request) SetCookiesRaw(cookies []*http.Cookie) *Request

SetCookiesRaw 设置原始 Cookie 切片

func (*Request) SetFormParam

func (r *Request) SetFormParam(key, value string) *Request

SetFormParam 设置单个表单参数

func (*Request) SetFormParams

func (r *Request) SetFormParams(params map[string]string) *Request

SetFormParams 设置多个表单参数

func (*Request) SetHeader

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

SetHeader 设置单个请求头

func (*Request) SetHeaders

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

SetHeaders 设置多个请求头

func (*Request) SetMethod

func (r *Request) SetMethod(method string) *Request

SetMethod 设置请求方法

func (*Request) SetQueryParam

func (r *Request) SetQueryParam(key, value string) *Request

SetQueryParam 设置单个查询参数

func (*Request) SetQueryParams

func (r *Request) SetQueryParams(params map[string]string) *Request

SetQueryParams 设置多个查询参数

type Response

type Response struct {
	*http.Response
	Err error
	// contains filtered or unexported fields
}

Response 封装了 HTTP 响应,提供了便捷的方法来处理响应。

func Get

func Get(url string, params, headers map[string]string) (*Response, error)

Get is a shortcut for doing a GET request without making a new client.

func Head(url string, params, headers map[string]string) (*Response, error)

Head is a shortcut for doing a HEAD request without making a new client.

func PostForm

func PostForm(url string, data, headers map[string]string) (*Response, error)

PostForm is a shortcut to perform a POST with form data without creating a new client.

func PostJSON

func PostJSON(url string, data any, headers map[string]string) (*Response, error)

PostJSON is a shortcut to perform a POST with JSON data without creating a new client.

func (*Response) Body

func (r *Response) Body() []byte

Body 返回响应体的字节数组。

func (*Response) DetectEncoding

func (r *Response) DetectEncoding() error

DetectEncoding 检测响应体的编码并转换为 UTF-8

func (*Response) GetCookies

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

GetCookies 获取响应的 Cookies

func (*Response) GetHeader

func (r *Response) GetHeader(key string) string

GetHeader 获取指定的响应头信息

func (*Response) GetHeaderValues

func (r *Response) GetHeaderValues(key string) []string

GetHeaderValues 获取指定的响应头的所有值

func (*Response) Gjson

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

Gjson 解析响应体为 gjson.Result

func (*Response) HasHeader

func (r *Response) HasHeader(key string) bool

HasHeader 检查指定的响应头是否存在

func (*Response) Header

func (r *Response) Header() http.Header

Header 返回响应的头部信息。

func (*Response) IsClientError

func (r *Response) IsClientError() bool

IsClientError 检查响应是否表示客户端错误。

func (*Response) IsServerError

func (r *Response) IsServerError() bool

IsServerError 检查响应是否表示服务器错误。

func (*Response) IsSuccess

func (r *Response) IsSuccess() bool

IsSuccess 检查响应是否表示成功的请求。

func (*Response) JSON

func (r *Response) JSON(v interface{}) error

JSON 解析响应体为 JSON。

func (*Response) PrettyPrint

func (r *Response) PrettyPrint() string

PrettyPrint 以易读的格式打印响应体

func (*Response) SaveToFile

func (r *Response) SaveToFile(filepath string) error

SaveToFile 将响应体保存到指定文件。

func (*Response) StatusCode

func (r *Response) StatusCode() int

StatusCode 返回响应的状态码。

func (*Response) String

func (r *Response) String() string

String 返回响应体的字符串表示。

func (*Response) ToBytesBuffer

func (r *Response) ToBytesBuffer() *bytes.Buffer

ToBytesBuffer 返回响应体的字节缓冲区。

func (*Response) ToMap

func (r *Response) ToMap() (map[string]interface{}, error)

ToMap 将响应体解析为 map。

type User

type User struct {
	Username, Password string
}

Jump to

Keyboard shortcuts

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