Skip to content

Commit

Permalink
Get Windows username
Browse files Browse the repository at this point in the history
  • Loading branch information
morestatic committed Jul 18, 2022
1 parent 8605f16 commit 4bf8529
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 3 deletions.
6 changes: 3 additions & 3 deletions internal/pkg/config/host.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package config

import (
"os"
"os/user"
"time"
)

Expand All @@ -13,7 +12,8 @@ type HostInfo struct {
}

func GetHostInfo() (hostInfo *HostInfo, err error) {
userInfo, err := user.Current()
var name string
name, err = userCurrent()
if err != nil {
return nil, err
}
Expand All @@ -23,7 +23,7 @@ func GetHostInfo() (hostInfo *HostInfo, err error) {
}
hostInfo = &HostInfo{
FetchedAt: time.Now(),
Username: userInfo.Name,
Username: name,
Machine: machine,
}
return hostInfo, nil
Expand Down
14 changes: 14 additions & 0 deletions internal/pkg/config/hostuser.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
//go:build darwin || linux
// +build darwin linux

package config

import "os/user"

func userCurrent() (string, error) {
userInfo, err := user.Current()
if err != nil {
return "", err
}
return userInfo.Name, nil
}
24 changes: 24 additions & 0 deletions internal/pkg/config/hostuser_win.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
//go:build windows
// +build windows

package config

import (
"errors"
"path/filepath"
"syscall"

"golang.org/x/sys/windows"
)

func userCurrent() (string, error) {
pw_name := make([]uint16, 256)
pwname_size := uint32(len(pw_name)) - 1
err := windows.GetUserNameEx(windows.NameSamCompatible, &pw_name[0], &pwname_size)
if err != nil {
return "", errors.New("unable to get windows user name")
}
s := syscall.UTF16ToString(pw_name)
u := filepath.Base(s)
return u, nil
}

0 comments on commit 4bf8529

Please sign in to comment.