ahttp

package
v1.8.7 Latest Latest
Warning

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

Go to latest
Published: Feb 10, 2025 License: Apache-2.0 Imports: 8 Imported by: 0

README

ahttp - HTTP客户端库 / HTTP Client Utilities

中文 | English


中文

📖 简介

ahttp 是一个高效、易用的HTTP客户端库,提供了简洁的API来发送HTTP请求并处理响应。它支持GET、POST、PUT、DELETE等多种HTTP方法,并且可以轻松地设置请求头、请求参数、超时时间等。ahttp 还内置了重试机制、连接池管理等功能,适用于各种HTTP请求场景。

GitHub地址: github.com/small-ek/antgo/net/ahttp

📦 安装
go get github.com/small-ek/antgo/net/ahttp
🚀 快速开始
发送GET请求
package main

import (
	"fmt"
	"github.com/small-ek/antgo/net/ahttp"
)

func main() {
	// 创建一个HTTP客户端
	client := ahttp.New()

	// 发送GET请求
	response, err := client.Get("https://jsonplaceholder.typicode.com/posts/1")
	if err != nil {
		fmt.Println("请求失败:", err)
		return
	}

	// 打印响应内容
	fmt.Println("响应状态码:", response.StatusCode())
	fmt.Println("响应体:", response.String())
}
发送POST请求
func main() {
	client := ahttp.New()

	// 设置请求体
	body := map[string]interface{}{
		"title":  "foo",
		"body":   "bar",
		"userId": 1,
	}

	// 发送POST请求
	response, err := client.Post("https://jsonplaceholder.typicode.com/posts", body)
	if err != nil {
		fmt.Println("请求失败:", err)
		return
	}

	// 打印响应内容
	fmt.Println("响应状态码:", response.StatusCode())
	fmt.Println("响应体:", response.String())
}
🔧 高级用法
设置请求头
func main() {
	client := ahttp.New()

	// 设置自定义请求头
	client.SetHeader("Authorization", "Bearer token123")
	client.SetHeader("Content-Type", "application/json")

	response, err := client.Get("https://jsonplaceholder.typicode.com/posts/1")
	if err != nil {
		fmt.Println("请求失败:", err)
		return
	}

	fmt.Println("响应体:", response.String())
}
设置超时时间
func main() {
	client := ahttp.New()

	// 设置请求超时时间为5秒
	client.SetTimeout(5 * time.Second)

	response, err := client.Get("https://jsonplaceholder.typicode.com/posts/1")
	if err != nil {
		fmt.Println("请求失败:", err)
		return
	}

	fmt.Println("响应体:", response.String())
}
使用重试机制
func main() {
	client := ahttp.New()

	// 设置重试次数为3次
	client.SetRetryCount(3)

	response, err := client.Get("https://jsonplaceholder.typicode.com/posts/1")
	if err != nil {
		fmt.Println("请求失败:", err)
		return
	}

	fmt.Println("响应体:", response.String())
}
✨ 核心特性
特性 描述
多方法支持 支持GET、POST、PUT、DELETE等多种HTTP方法
请求头设置 轻松设置自定义请求头
超时控制 支持设置请求超时时间
重试机制 内置请求重试机制,提高请求成功率
连接池管理 自动管理HTTP连接池,提升性能
⚠️ 注意事项
  1. 确保请求的URL是有效的
  2. 设置合理的超时时间以避免请求长时间挂起
  3. 使用重试机制时,注意服务器的负载情况
  4. 对于敏感数据,建议使用HTTPS协议
🤝 参与贡献

贡献指南 | 提交Issue


English

📖 Introduction

ahttp is an efficient and easy-to-use HTTP client library that provides a simple API for sending HTTP requests and handling responses. It supports various HTTP methods such as GET, POST, PUT, DELETE, and allows easy configuration of request headers, parameters, and timeout settings. ahttp also includes features like retry mechanism and connection pool management, making it suitable for various HTTP request scenarios.

GitHub URL: github.com/small-ek/antgo/net/ahttp

📦 Installation
go get github.com/small-ek/antgo/net/ahttp
🚀 Quick Start
Sending a GET Request
package main

import (
	"fmt"
	"github.com/small-ek/antgo/net/ahttp"
)

func main() {
	client := ahttp.New()

	response, err := client.Get("https://jsonplaceholder.typicode.com/posts/1")
	if err != nil {
		fmt.Println("Request failed:", err)
		return
	}

	fmt.Println("Response status code:", response.StatusCode())
	fmt.Println("Response body:", response.String())
}
Sending a POST Request
func main() {
	client := ahttp.New()

	body := map[string]interface{}{
		"title":  "foo",
		"body":   "bar",
		"userId": 1,
	}

	response, err := client.Post("https://jsonplaceholder.typicode.com/posts", body)
	if err != nil {
		fmt.Println("Request failed:", err)
		return
	}

	fmt.Println("Response status code:", response.StatusCode())
	fmt.Println("Response body:", response.String())
}
🔧 Advanced Usage
Setting Request Headers
func main() {
	client := ahttp.New()

	client.SetHeader("Authorization", "Bearer token123")
	client.SetHeader("Content-Type", "application/json")

	response, err := client.Get("https://jsonplaceholder.typicode.com/posts/1")
	if err != nil {
		fmt.Println("Request failed:", err)
		return
	}

	fmt.Println("Response body:", response.String())
}
Setting Timeout
func main() {
	client := ahttp.New()

	client.SetTimeout(5 * time.Second)

	response, err := client.Get("https://jsonplaceholder.typicode.com/posts/1")
	if err != nil {
		fmt.Println("Request failed:", err)
		return
	}

	fmt.Println("Response body:", response.String())
}
Using Retry Mechanism
func main() {
	client := ahttp.New()

	client.SetRetryCount(3)

	response, err := client.Get("https://jsonplaceholder.typicode.com/posts/1")
	if err != nil {
		fmt.Println("Request failed:", err)
		return
	}

	fmt.Println("Response body:", response.String())
}
✨ Key Features
Feature Description
Multi-method Supports GET, POST, PUT, DELETE, and more
Header Setting Easy configuration of custom request headers
Timeout Control Supports setting request timeout
Retry Mechanism Built-in retry mechanism to improve request success rate
Connection Pool Automatic management of HTTP connection pool for better performance
⚠️ Important Notes
  1. Ensure the request URL is valid
  2. Set a reasonable timeout to avoid long hanging requests
  3. Be mindful of server load when using the retry mechanism
  4. Use HTTPS for sensitive data
🤝 Contributing

Contribution Guide | Open an Issue

⬆ Back to Top

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config added in v1.8.6

type Config struct {
	MaxIdleConnections    int           // 连接池的最大空闲连接数 / Maximum idle connections in the connection pool
	IdleConnectionTimeout time.Duration // 空闲连接超时时间 / Timeout for idle connections
	DisableCompression    bool          // 禁用压缩 / Disable compression
	DisableKeepAlives     bool          // 禁用 keep-alive / Disable keep-alive
	InsecureSkipVerify    bool          // 跳过 TLS 证书验证 / Skip TLS certificate verification
	Timeout               time.Duration // 总超时时间 / Total timeout duration
	TLSHandshakeTimeout   time.Duration // TLS 握手超时时间 / Timeout for TLS handshake
	ExpectContinueTimeout time.Duration // 100-continue 超时时间 / Timeout for 100-continue
	MaxConnectionsPerHost int           // 每主机的最大连接数 / Maximum connections per host
	RetryAttempts         int           // 请求重试次数 / Number of retry attempts for failed requests
	DialerTimeout         time.Duration // Dialer 的连接超时时间 / Dialer connection timeout
	DialerKeepAlive       time.Duration // Dialer 的 Keep-Alive 时间 / Dialer keep-alive time
	RetryWaitTime         time.Duration // 重试等待时间 / RetryWaitTime
	RetryMaxWaitTime      time.Duration // 最大重试等待时间 / RetryMaxWaitTime
}

Config 包含 HTTP 客户端的配置选项 Config contains the configuration options for the HTTP client

type HttpClient added in v1.8.6

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

HttpClient 是对 Resty 客户端的封装,支持自定义配置和日志 / HttpClient is a wrapper for the Resty client with custom configuration and logging support

func New added in v1.8.6

func New(config *Config) *HttpClient

New 创建一个新的 HTTP 客户端实例 / NewHttpClient creates a new HTTP client instance

func (*HttpClient) Client added in v1.8.6

func (h *HttpClient) Client() *resty.Client

Client 返回 Resty 客户端实例 / Returns the Resty client instance

func (*HttpClient) Request added in v1.8.6

func (h *HttpClient) Request() *resty.Request

Request 返回 Resty 请求实例 / Returns the Resty request instance

func (*HttpClient) SetLog added in v1.8.6

func (h *HttpClient) SetLog(logger *zap.Logger) *HttpClient

SetLog 设置日志记录器 / SetLog sets the logger

Jump to

Keyboard shortcuts

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