From 3963fce43b67119e574b3bce1c878546c13b43b1 Mon Sep 17 00:00:00 2001 From: Cuong Manh Le Date: Thu, 21 Mar 2024 18:27:25 +0700 Subject: [PATCH] Use sync.OnceValue --- doh.go | 19 ++++++------------- doh_test.go | 2 +- 2 files changed, 7 insertions(+), 14 deletions(-) diff --git a/doh.go b/doh.go index 239fd6f..870d5bd 100644 --- a/doh.go +++ b/doh.go @@ -60,17 +60,10 @@ func init() { } } -// TODO: use sync.OnceValue when upgrading to go1.21 -var xCdOsValueOnce sync.Once -var xCdOsValue string - -func dohOsHeaderValue() string { - xCdOsValueOnce.Do(func() { - oi := osinfo.New() - xCdOsValue = strings.Join([]string{EncodeOsNameMap[runtime.GOOS], EncodeArchNameMap[runtime.GOARCH], oi.Dist}, "-") - }) - return xCdOsValue -} +var dohOsHeaderValue = sync.OnceValue(func() string { + oi := osinfo.New() + return strings.Join([]string{EncodeOsNameMap[runtime.GOOS], EncodeArchNameMap[runtime.GOARCH], oi.Dist}, "-") +})() func newDohResolver(uc *UpstreamConfig) *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. func newControlDHeaders(ci *ClientInfo) http.Header { header := make(http.Header) - header.Set(dohOsHeader, dohOsHeaderValue()) + header.Set(dohOsHeader, dohOsHeaderValue) if ci.Mac != "" { header.Set(dohMacHeader, ci.Mac) } @@ -183,7 +176,7 @@ func newControlDHeaders(ci *ClientInfo) http.Header { header.Set(dohHostHeader, ci.Hostname) } if ci.Self { - header.Set(dohOsHeader, dohOsHeaderValue()) + header.Set(dohOsHeader, dohOsHeaderValue) } switch ci.ClientIDPref { case "mac": diff --git a/doh_test.go b/doh_test.go index d233498..8d3e011 100644 --- a/doh_test.go +++ b/doh_test.go @@ -6,7 +6,7 @@ import ( ) func Test_dohOsHeaderValue(t *testing.T) { - val := dohOsHeaderValue() + val := dohOsHeaderValue if val == "" { t.Fatalf("empty %s", dohOsHeader) }