Use sync.OnceValue

This commit is contained in:
Cuong Manh Le
2024-03-22 16:29:54 +07:00
committed by Cuong Manh Le
parent ea4e5147bd
commit 3963fce43b
2 changed files with 7 additions and 14 deletions
+6 -13
View File
@@ -60,17 +60,10 @@ func init() {
} }
} }
// TODO: use sync.OnceValue when upgrading to go1.21 var dohOsHeaderValue = sync.OnceValue(func() string {
var xCdOsValueOnce sync.Once oi := osinfo.New()
var xCdOsValue string return strings.Join([]string{EncodeOsNameMap[runtime.GOOS], EncodeArchNameMap[runtime.GOARCH], oi.Dist}, "-")
})()
func dohOsHeaderValue() string {
xCdOsValueOnce.Do(func() {
oi := osinfo.New()
xCdOsValue = strings.Join([]string{EncodeOsNameMap[runtime.GOOS], EncodeArchNameMap[runtime.GOARCH], oi.Dist}, "-")
})
return xCdOsValue
}
func newDohResolver(uc *UpstreamConfig) *dohResolver { func newDohResolver(uc *UpstreamConfig) *dohResolver {
r := &dohResolver{ r := &dohResolver{
@@ -172,7 +165,7 @@ func addHeader(ctx context.Context, req *http.Request, uc *UpstreamConfig) {
// newControlDHeaders returns DoH/Doh3 HTTP request headers for ControlD upstream. // newControlDHeaders returns DoH/Doh3 HTTP request headers for ControlD upstream.
func newControlDHeaders(ci *ClientInfo) http.Header { func newControlDHeaders(ci *ClientInfo) http.Header {
header := make(http.Header) header := make(http.Header)
header.Set(dohOsHeader, dohOsHeaderValue()) header.Set(dohOsHeader, dohOsHeaderValue)
if ci.Mac != "" { if ci.Mac != "" {
header.Set(dohMacHeader, ci.Mac) header.Set(dohMacHeader, ci.Mac)
} }
@@ -183,7 +176,7 @@ func newControlDHeaders(ci *ClientInfo) http.Header {
header.Set(dohHostHeader, ci.Hostname) header.Set(dohHostHeader, ci.Hostname)
} }
if ci.Self { if ci.Self {
header.Set(dohOsHeader, dohOsHeaderValue()) header.Set(dohOsHeader, dohOsHeaderValue)
} }
switch ci.ClientIDPref { switch ci.ClientIDPref {
case "mac": case "mac":
+1 -1
View File
@@ -6,7 +6,7 @@ import (
) )
func Test_dohOsHeaderValue(t *testing.T) { func Test_dohOsHeaderValue(t *testing.T) {
val := dohOsHeaderValue() val := dohOsHeaderValue
if val == "" { if val == "" {
t.Fatalf("empty %s", dohOsHeader) t.Fatalf("empty %s", dohOsHeader)
} }