I'm learning and trying out golang to create an application that needs access to user home directory.
To make easier to understand the problem, consider this main.go:
package main
import (
"fmt"
"os"
)
func main() {
home, err := os.UserHomeDir()
if err != nil {
fmt.Printf("Err: %s\n", err)
os.Exit(1)
} else {
fmt.Printf("HOME: %s\n", home)
os.Exit(0)
}
}
After building the application I tried to run it on windows and macos and the output worked well.
For linux, I tried to run on WSL, I don't know if that's the problem
HOME: C:\Users\<user>
echo $HOME
and it showed the correct homedir.os.Getenv("HOME")
and was printing emptygo build -o C:/_builds/.bin/example .
cd /mnt/c/_builds/.bin
And run the command
./example
I've ommited my machine information and username
Do you have any ideas? Am I missing something?
You're building a Windows binary.
When you execute it in the WSL environment, it's still a Windows binary, still retains the runtime.GOOS
value set at compile time, and will still trigger the Windows specific code path in the os.UserHomeDir()
implementation.
To build a Linux binary, try setting the GOOS
environment variable before running the go build
command. Something like:
set GOOS="linux"
go build -o C:/_builds/.bin/example_linux .
The full set of environment variables that influence operation of the go
command are documented at https://pkg.go.dev/cmd/go#hdr-Environment_variables.
For background on WSL supporting execution of Windows executables see https://learn.microsoft.com/en-us/windows/wsl/filesystems#run-windows-tools-from-linux.