Files
kirogo/auth/http_client.go
2026-05-12 18:04:58 +08:00

51 lines
1.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Package auth 提供认证相关功能的 HTTP 客户端
package auth
import (
"net/http"
"net/url"
"sync/atomic"
"time"
)
// 全局 HTTP 客户端存储,支持运行时代理重配置
var httpClientStore atomic.Pointer[http.Client]
// httpClient 返回当前全局 auth HTTP 客户端
func httpClient() *http.Client {
return httpClientStore.Load()
}
func init() {
InitHttpClient("")
}
// buildAuthTransport 构建带可选代理的 Transport
func buildAuthTransport(proxyURL string) *http.Transport {
t := &http.Transport{
MaxIdleConns: 50,
MaxIdleConnsPerHost: 10,
IdleConnTimeout: 90 * time.Second,
DisableCompression: false,
ForceAttemptHTTP2: true,
}
if proxyURL != "" {
if u, err := url.Parse(proxyURL); err == nil {
t.Proxy = http.ProxyURL(u)
t.ForceAttemptHTTP2 = false
}
} else {
t.Proxy = http.ProxyFromEnvironment
}
return t
}
// InitHttpClient 初始化或重新初始化auth 模块的全局 HTTP 客户端
func InitHttpClient(proxyURL string) {
client := &http.Client{
Timeout: 30 * time.Second,
Transport: buildAuthTransport(proxyURL),
}
httpClientStore.Store(client)
}