net: simplify readProtocols via sync.OnceFunc

In this case, using sync.OnceFunc is a better choice.

Change-Id: I52d27b9741265c90300a04a03537020e1aaaaaa7
GitHub-Last-Rev: a281daea255f1508a9042e8c8c7eb7ca1cef2430
GitHub-Pull-Request: golang/go#73434
Reviewed-on: https://go-review.googlesource.com/c/go/+/666635
Reviewed-by: David Chase <drchase@google.com>
Auto-Submit: Jorropo <jorropo.pgm@gmail.com>
Reviewed-by: Damien Neil <dneil@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Jorropo <jorropo.pgm@gmail.com>
This commit is contained in:
1911860538 2025-04-18 14:11:29 +00:00 committed by Gopher Robot
parent ad0434200c
commit a204ed53d9

View File

@ -12,11 +12,9 @@ import (
"sync" "sync"
) )
var onceReadProtocols sync.Once // readProtocolsOnce loads contents of /etc/protocols into protocols map
// readProtocols loads contents of /etc/protocols into protocols map
// for quick access. // for quick access.
func readProtocols() { var readProtocolsOnce = sync.OnceFunc(func() {
file, err := open("/etc/protocols") file, err := open("/etc/protocols")
if err != nil { if err != nil {
return return
@ -43,12 +41,12 @@ func readProtocols() {
} }
} }
} }
} })
// lookupProtocol looks up IP protocol name in /etc/protocols and // lookupProtocol looks up IP protocol name in /etc/protocols and
// returns correspondent protocol number. // returns correspondent protocol number.
func lookupProtocol(_ context.Context, name string) (int, error) { func lookupProtocol(_ context.Context, name string) (int, error) {
onceReadProtocols.Do(readProtocols) readProtocolsOnce()
return lookupProtocolMap(name) return lookupProtocolMap(name)
} }