fix: make doh truly singleton

This commit is contained in:
ohaiibuzzle 2024-08-11 19:35:02 +07:00
parent c93ddd67e0
commit e9de332163

View File

@ -8,6 +8,7 @@ import (
"net" "net"
"net/http" "net/http"
"strings" "strings"
"sync"
"time" "time"
"github.com/miekg/dns" "github.com/miekg/dns"
@ -20,35 +21,38 @@ type DoHClient struct {
} }
var client *DoHClient var client *DoHClient
var clientOnce sync.Once
func GetDoHClient(upstream string) *DoHClient { func GetDoHClient(upstream string) *DoHClient {
if client == nil { clientOnce.Do(func() {
if !strings.HasPrefix(upstream, "https://") { if client == nil {
upstream = "https://" + upstream if !strings.HasPrefix(upstream, "https://") {
} upstream = "https://" + upstream
}
if !strings.HasSuffix(upstream, "/dns-query") { if !strings.HasSuffix(upstream, "/dns-query") {
upstream = upstream + "/dns-query" upstream = upstream + "/dns-query"
} }
c := &http.Client{ c := &http.Client{
Timeout: 5 * time.Second, Timeout: 5 * time.Second,
Transport: &http.Transport{ Transport: &http.Transport{
DialContext: (&net.Dialer{ DialContext: (&net.Dialer{
Timeout: 3 * time.Second, Timeout: 3 * time.Second,
KeepAlive: 30 * time.Second, KeepAlive: 30 * time.Second,
}).DialContext, }).DialContext,
TLSHandshakeTimeout: 5 * time.Second, TLSHandshakeTimeout: 5 * time.Second,
MaxIdleConnsPerHost: 100, MaxIdleConnsPerHost: 100,
MaxIdleConns: 100, MaxIdleConns: 100,
}, },
} }
client = &DoHClient{ client = &DoHClient{
upstream: upstream, upstream: upstream,
c: c, c: c,
}
} }
} })
return client return client
} }