Last active
March 13, 2021 20:02
-
-
Save bradleypeabody/10572010 to your computer and use it in GitHub Desktop.
Implementing Symlink in go on Windows
This file contains hidden or 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 ( | |
"os" | |
"syscall" | |
"unsafe" | |
) | |
var ( | |
k32 = syscall.MustLoadDLL("kernel32.dll") | |
createSymbolicLink = k32.MustFindProc("CreateSymbolicLinkW") | |
) | |
func Symlink(oldpath, newpath string) error { | |
// look at target and see if it's a file or dir | |
st, err := os.Stat(oldpath) | |
if err != nil { | |
return err | |
} | |
// CreateSymbolicLink expects a 0 to link a file and 1 to link a dir | |
linkType := 0 | |
if st.Mode() == os.ModeDir { | |
linkType = 1 | |
} | |
// do the call | |
_, _, callErr := createSymbolicLink.Call( | |
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(newpath))), | |
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(oldpath))), | |
uintptr(linkType), | |
) | |
// check for error | |
errno, _ := callErr.(syscall.Errno) | |
if errno != 0 { | |
return callErr | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment