Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using OS targeted go files to separate out the username logic. #271

Merged
merged 1 commit into from Dec 18, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
34 changes: 0 additions & 34 deletions klog_file.go
Expand Up @@ -22,9 +22,7 @@ import (
"errors"
"fmt"
"os"
"os/user"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -57,38 +55,6 @@ func init() {
}
}

func getUserName() string {
userNameOnce.Do(func() {
// 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)

// 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
}
}
})

return userName
}

// shortHostname returns its argument, truncating at the first period.
// For instance, given "www.google.com" it returns "www".
func shortHostname(hostname string) string {
Expand Down
19 changes: 19 additions & 0 deletions klog_file_others.go
@@ -0,0 +1,19 @@
//go:build !windows
// +build !windows

package klog

import (
"os/user"
)

func getUserName() string {
userNameOnce.Do(func() {
current, err := user.Current()
if err == nil {
userName = current.Username
}
})

return userName
}
34 changes: 34 additions & 0 deletions klog_file_windows.go
@@ -0,0 +1,34 @@
//go:build windows
// +build windows

package klog

import (
"os"
"strings"
)

func getUserName() string {
userNameOnce.Do(func() {
// 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.
u := os.Getenv("USERNAME")
if len(u) == 0 {
return
}
// Sanitize the USERNAME since it may contain filepath separators.
u = strings.Replace(u, `\`, "_", -1)

// user.Current().Username normally produces something like 'USERDOMAIN\USERNAME'
d := os.Getenv("USERDOMAIN")
if len(d) != 0 {
userName = d + "_" + u
} else {
userName = u
}
})

return userName
}