{"record":{"id":"6e5f9b24bdebcf62","repo":"unknwon/the-way-to-go_ZH_CN","slug":"unknown-user-no-value-for-user","errorCode":null,"errorMessage":"Unknown user: no value for $USER","messagePattern":"Unknown user: no value for \\$USER","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"eBook/13.2.md","lineNumber":44,"sourceCode":"       runtime.panic(0x442938, 0x4f08e8)\nmain.main+0xa5 E:/Go/GoBoek/code examples/chapter 13/panic.go:8\n       main.main()\nruntime.mainstart+0xf 386/asm.s:84\n       runtime.mainstart()\nruntime.goexit /go/src/pkg/runtime/proc.c:148\n       runtime.goexit()\n---- Error run E:/Go/GoBoek/code examples/chapter 13/panic.exe with code Crashed\n---- Program exited with code -1073741783\n```\n\n一个检查程序是否被已知用户启动的具体例子：\n\n```go\nvar user = os.Getenv(\"USER\")\n\nfunc check() {\n\tif user == \"\" {\n\t\tpanic(\"Unknown user: no value for $USER\")\n\t}\n}\n```\n\n可以在导入包的 `init()` 函数中检查这些。\n\n当发生错误必须中止程序时，`panic()` 可以用于错误处理模式：\n\n```go\nif err != nil {\n\tpanic(\"ERROR occurred:\" + err.Error())\n}\n```\n\n<u>Go panicking</u>：\n\n在多层嵌套的函数调用中调用 `panic()`，可以马上中止当前函数的执行，所有的 `defer` 语句都会保证执行并把控制权交还给接收到 panic 的函数调用者。这样向上冒泡直到最顶层，并执行（每层的） `defer`，在栈顶处程序崩溃，并在命令行中用传给 `panic()` 的值报告错误情况：这个终止过程就是 *panicking*。\n","sourceCodeStart":26,"sourceCodeEnd":62,"githubUrl":"https://github.com/unknwon/the-way-to-go_ZH_CN/blob/7a54d34d3657084b6a59e5618bd069b912d571aa/eBook/13.2.md#L26-L62","documentation":"Init-style guard from section 13.2: the package reads os.Getenv(\"USER\") once at startup and check() panics with 'Unknown user: no value for $USER' when it is empty, refusing to run for an unidentified user. The text recommends performing such checks in an imported package's init() so the program fails immediately at load time.","triggerScenarios":"os.Getenv(\"USER\") returns \"\": the variable is unset or empty in minimal shells, cron/systemd/Docker environments that scrub the environment, or on Windows where the conventional variable is USERNAME, not USER.","commonSituations":"Running the program on Windows; executing via crontab or a systemd unit without Environment= configured; slim Docker images with non-login shells; CI runners with restricted env.","solutions":["Set the variable before running: export USER=$(whoami) on Unix, or set USER=%USERNAME% on Windows","Replace the panic with a runtime fallback: use os/user.Current().Username when USER is empty","For services, configure the environment properly (systemd Environment=, docker -e USER=...)","Fail with log.Fatal instead of panic so the process exits cleanly with the message"],"exampleFix":"// before\nvar user = os.Getenv(\"USER\")\nfunc check() {\n    if user == \"\" {\n        panic(\"Unknown user: no value for $USER\")\n    }\n}\n\n// after\nfunc check() error {\n    if os.Getenv(\"USER\") == \"\" {\n        if u, err := user.Current(); err == nil && u.Username != \"\" {\n            os.Setenv(\"USER\", u.Username)\n            return nil\n        }\n        return errors.New(\"unknown user: no value for $USER\")\n    }\n    return nil\n}","handlingStrategy":"validation","validationCode":"// run before the program (shell):\n[ -z \"$USER\" ] && export USER=\"$(whoami)\"\n\n// or in Go, before calling anything that needs it:\nif os.Getenv(\"USER\") == \"\" {\n    if u, err := user.Current(); err == nil {\n        os.Setenv(\"USER\", u.Username)\n    }\n}","typeGuard":null,"tryCatchPattern":"defer func() {\n    if r := recover(); r != nil {\n        if strings.Contains(fmt.Sprint(r), \"$USER\") {\n            log.Fatal(\"set USER and retry (Windows: set USER=%USERNAME%)\")\n        }\n        panic(r)\n    }\n}()","preventionTips":["Never assume $USER exists — Windows uses USERNAME and services often scrub env","Prefer os/user.Current().Username as a portable identity source","Configure Environment= in systemd units and -e in docker for services that read env identity"],"tags":["go","environment-variables","panic","cross-platform","windows","init"],"backgroundTag":null,"analyzedSha":"7a54d34d3657084b6a59e5618bd069b912d571aa","analyzedAt":"2026-08-15T15:13:06.026Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}