1 Star 0 Fork 0

wait4me/selfGoLib

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
https.go 1.60 KB
一键复制 编辑 原始数据 按行查看 历史
wait4me 提交于 2026-02-11 14:06 +08:00 . feat: initial release of selfGoLib toolkit
package httpsUtil
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/json"
"io"
"net/http"
"time"
)
func PostJson(url string, reqData map[string]any) (int, []byte, error) {
jsonData, err := json.Marshal(reqData)
if err != nil {
return -1, nil, err
}
// 创建请求
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
return -1, nil, err
}
req.Header.Set("Content-Type", "application/json;charset=utf-8")
req.Header.Set("User-Agent", "Go-HTTPS-Client/1.0")
// 创建自定义验证函数
customVerify := func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
cert, _ := x509.ParseCertificate(rawCerts[0])
// 检查 IP 是否匹配(跳过 SAN 检查)
ip := "9.80.35.166"
for _, addr := range cert.IPAddresses {
if addr.String() == ip {
return nil // IP 匹配
}
}
return x509.CertificateInvalidError{
Cert: cert,
Reason: x509.NameMismatch,
}
}
// 配置 TLS
conf := &tls.Config{
ServerName: "9.80.35.166",
InsecureSkipVerify: true, // 跳过默认验证
VerifyPeerCertificate: customVerify, // 使用自定义验证
}
// 创建客户端
client := &http.Client{
Timeout: 10 * time.Second,
Transport: &http.Transport{
TLSClientConfig: conf,
},
}
// 发送请求
resp, err := client.Do(req)
if err != nil {
return -1, nil, err
}
defer resp.Body.Close()
// 读取响应
body, err := io.ReadAll(resp.Body)
if err != nil {
return -1, nil, err
}
// fmt.Printf("状态码: %d\n", resp.StatusCode)
// fmt.Printf("响应体: %s\n", body)
return resp.StatusCode, body, nil
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/wait4me/selfGoLib.git
git@gitee.com:wait4me/selfGoLib.git
wait4me
selfGoLib
selfGoLib
v1.0.3

搜索帮助