Skip to content
鼓励作者:欢迎打赏犒劳

httpClient请求工具类

工具类

支持:纯get请求

post请求:json格式

go
package main

import (
	"bytes"
	"encoding/json"
	"io"
	"net/http"
)

// HTTPClient 是一个通用 HTTP 客户端工具
type HTTPClient struct {
	client *http.Client
}

// NewHTTPClient 创建一个新的 HTTP 客户端
func NewHTTPClient() *HTTPClient {
	return &HTTPClient{
		client: &http.Client{},
	}
}

// RequestConfig 定义请求的配置参数
type RequestConfig struct {
	URL     string
	Method  string
	Headers map[string]string
	Body    interface{} // JSON serializable data
}

// Response 封装响应结果
type Response struct {
	StatusCode int
	Body       []byte
	Header     http.Header
}

// Do 发送 HTTP 请求并返回响应和错误
func (c *HTTPClient) Do(config RequestConfig) (*Response, error) {
	// 序列化 JSON 请求体(如果存在)
	var bodyReader io.Reader
	if config.Body != nil {
		jsonData, err := json.Marshal(config.Body)
		if err != nil {
			return nil, err
		}
		bodyReader = bytes.NewBuffer(jsonData)
	}

	// 创建请求
	req, err := http.NewRequest(config.Method, config.URL, bodyReader)
	if err != nil {
		return nil, err
	}

	// 设置 Headers
	if config.Headers != nil {
		for key, value := range config.Headers {
			req.Header.Set(key, value)
		}
	}

	// 确保 Content-Type 默认为 application/json(如果未设置且有 body)
	if config.Body != nil {
		if _, exists := config.Headers["Content-Type"]; !exists {
			req.Header.Set("Content-Type", "application/json")
		}
	}

	// 发送请求
	resp, err := c.client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	// 读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	// 返回封装的响应
	return &Response{
		StatusCode: resp.StatusCode,
		Body:       body,
		Header:     resp.Header,
	}, nil
}

使用示例

go
func main() {
	// 创建客户端
	client := NewHTTPClient()

	// 构造请求参数
	requestBody := map[string]interface{}{
		"biz":         1775,
		"name":        "xxx",
		"template_id": 265260,
		"app":  map[string]interface{}{
			"url": "https:/test.com/base/file/s/obj/thubservice-public/e154fb93b10342743c409f7a9154bdce.apk",
		},
	}

	// 配置请求
	config := RequestConfig{
		URL:    "https://test.com/auto_test/api/v1/task",
		Method: "POST",
		Headers: map[string]string{
			"Authorization": "Bearer xxxxxxxxxxxxxxxxxxxx",
			// Content-Type 会自动设置为 application/json
		},
		Body: requestBody,
	}

	// 发送请求
	resp, err := client.Do(config)
	if err != nil {
		panic(err)
	}

	// 输出结果
	println("Status Code:", resp.StatusCode)
	println("Response Body:", string(resp.Body))
}

支持 GET 请求

go
config := RequestConfig{
    URL:    "https://api.example.com/data",
    Method: "GET",
    Headers: map[string]string{
        "Authorization": "Bearer xxx",
    },
    Body: nil, // GET 请求通常无 body
}

如有转载或 CV 的请标注本站原文地址