Skip to content

Instantly share code, notes, and snippets.

@groob
Created June 14, 2017 02:11
Show Gist options
  • Save groob/178dea728b4640b2fec9ca05106a4027 to your computer and use it in GitHub Desktop.
Save groob/178dea728b4640b2fec9ca05106a4027 to your computer and use it in GitHub Desktop.
package main
/*
#cgo LDFLAGS: -framework SystemConfiguration
#include <SystemConfiguration/SystemConfiguration.h>
#include <stdlib.h>
*/
import "C"
import (
"errors"
"fmt"
"log"
"os/user"
)
func main() {
u, err := currentMacOSUser()
if err != nil {
log.Fatal(err)
}
fmt.Println(u.Username)
}
// currentMacOSUser calls SCDynamicStoreCopyConsoleUser
// to get the current macOS logged in user.
func currentMacOSUser() (*user.User, error) {
uid := new(C.uid_t)
C.SCDynamicStoreCopyConsoleUser(nil, uid, nil)
if uid == nil {
return nil, errors.New("failed to lookup macOS console user")
}
return user.LookupId(fmt.Sprintf("%d", *uid))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment