Created
April 2, 2019 07:30
-
-
Save microo8/c1b9525efab9bb462adf9d123e855c52 to your computer and use it in GitHub Desktop.
Append PATH on windows in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"os" | |
"syscall" | |
"unsafe" | |
"golang.org/x/sys/windows/registry" | |
) | |
//const ... | |
const ( | |
pathRegKey = "Path" | |
HWND_BROADCAST = uintptr(0xffff) | |
WM_SETTINGCHANGE = uintptr(0x001A) | |
) | |
func getRegEnvValue(key string) (string, error) { | |
k, err := registry.OpenKey(registry.LOCAL_MACHINE, `System\CurrentControlSet\Control\Session Manager\Environment`, registry.QUERY_VALUE) | |
if err != nil { | |
return "", err | |
} | |
defer k.Close() | |
s, _, err := k.GetStringValue(key) | |
return s, err | |
} | |
func saveRegEnvValue(key string, value string) error { | |
k, err := registry.OpenKey(registry.LOCAL_MACHINE, `System\CurrentControlSet\Control\Session Manager\Environment`, registry.SET_VALUE) | |
if err != nil { | |
return err | |
} | |
defer k.Close() | |
return k.SetStringValue(key, value) | |
} | |
//AppendPath ... | |
func AppendPath(newPath string) { | |
path, err := getRegEnvValue(pathRegKey) | |
if err != nil { | |
log.Fatal("GetStringValue", err) | |
} | |
if err := saveRegEnvValue(pathRegKey, path+string(os.PathListSeparator)+newPath); err != nil { | |
log.Fatal("SetStringValue", err) | |
} | |
syscall.NewLazyDLL("user32.dll").NewProc("SendMessageW").Call(HWND_BROADCAST, WM_SETTINGCHANGE, 0, uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("ENVIRONMENT")))) | |
} | |
func main() { | |
AppendPath("C:\\test") | |
fmt.Scanln() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment