Look Up Users With os/user
Resolve the current account and a named user through os/user, reading username, uid, gid, home directory, and group IDs.
Code
package main
import (
"fmt"
"os/user"
)
func main() {
// Current 读取运行进程的有效用户
current, err := user.Current()
if err != nil {
fmt.Println("current user failed:", err)
return
}
fmt.Println("username:", current.Username)
fmt.Println("uid:", current.Uid, "gid:", current.Gid)
fmt.Println("home:", current.HomeDir)
// Lookup 解析指定用户名,找不到时返回 UnknownUserError
lookup, err := user.Lookup(current.Username)
if err != nil {
fmt.Println("lookup failed:", err)
return
}
fmt.Println("resolved name:", lookup.Name)
fmt.Println("same uid:", lookup.Uid == current.Uid)
// GroupIds 返回用户所属组的 ID 列表
gids, err := current.GroupIds()
if err != nil {
fmt.Println("group lookup unsupported:", err)
} else {
fmt.Println("group count:", len(gids))
}
// 未注册的名字会明确失败,而不是返回零值
_, err = user.Lookup("no-such-user-42")
fmt.Println("missing user error:", err != nil)
}Inside the snippet
Look Up Users With os/user reduces to the function main.
err is inspected at 3 call sites before any result is trusted.
Using it
The run emits 10 labeled sections — current user failed:, username:, uid:, home:, lookup failed:, resolved name:, same uid:, group lookup unsupported:, group count:, missing user error: — one per step.
Key statements
if err != nil {
fmt.Println("current user failed:", err)
return
}
if err != nil {
fmt.Println("lookup failed:", err)
return
}
if err != nil {
fmt.Println("group lookup unsupported:", err)
} else {
fmt.Println("group count:", len(gids))
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
FAQ
- What does Look Up Users With os/user print when run?
- Execute the whole file; each printed line is prefixed with a label like `current user failed:`, `username:`, `uid:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.