Skip to content

Commit

Permalink
klog_file: workaround stdlib.user not supporting Nano Server
Browse files Browse the repository at this point in the history
user.Current() can panic on Windows if the OS is missing
netapi32.dll. This library is stripped from Windows Nano Server.

To workaround this, use environment variables on all versions
on Windows.
  • Loading branch information
neolit123 committed Mar 6, 2020
1 parent 12be8a0 commit c46b9e1
Showing 1 changed file with 25 additions and 6 deletions.
31 changes: 25 additions & 6 deletions klog_file.go
Expand Up @@ -24,6 +24,7 @@ import (
"os"
"os/user"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -55,13 +56,31 @@ func init() {
host = shortHostname(h)
}

current, err := user.Current()
if err == nil {
userName = current.Username
}
// On Windows, the Go 'user' package requires netapi32.dll.
// This affects Windows Nano Server:
// https://github.com/golang/go/issues/21867
// Fallback to using environment variables.
if runtime.GOOS == "windows" {
u := os.Getenv("USERNAME")
if len(u) == 0 {
return
}
// Sanitize the USERNAME since it may contain filepath separators.
u = strings.Replace(u, `\`, "_", -1)

// Sanitize userName since it may contain filepath separators on Windows.
userName = strings.Replace(userName, `\`, "_", -1)
// user.Current().Username normally produces something like 'USERDOMAIN\USERNAME'
d := os.Getenv("USERDOMAIN")
if len(d) != 0 {
userName = d + "_" + u
} else {
userName = u
}
} else {
current, err := user.Current()
if err == nil {
userName = current.Username
}
}
}

// shortHostname returns its argument, truncating at the first period.
Expand Down

0 comments on commit c46b9e1

Please sign in to comment.