go os/user.Current() returns empty Name on alpine 3.15/go1.17.4
The Go function os/user.Current() returns a User with an empty Name. The user Uid is correct.
Steps to reproduce
On a new alpine 3.15 system:
- create a file user.go with the content:
package main
import (
"fmt"
"os/user"
)
func main() {
u, err := user.Current()
if err != nil {
fmt.Printf("error: %v\n", err)
return
}
fmt.Printf("name=%s uid=%s\n", u.Name, u.Uid)
}
- Install go and run user.go:
apk add go
go run user.go
Result: the current user name is not printed.
Expected Result: the current user name (e.g. "root") should be printed.
It works correctly on alpine 3.14, with go1.16.10.
Workaround
Luckily, there is a workaround. Add this line to the very beginning of the go file:
// +build osusergo
This is documented in "go doc os/user":
package user // import "os/user"
Package user allows user account lookups by name or id.
For most Unix systems, this package has two internal implementations of
resolving user and group ids to names. One is written in pure Go and parses
/etc/passwd and /etc/group. The other is cgo-based and relies on the
standard C library (libc) routines such as getpwuid_r and getgrnam_r.
When cgo is available, cgo-based (libc-backed) code is used by default. This
can be overridden by using osusergo build tag, which enforces the pure Go
implementation.