文章标签 » golang

Mount network location in Golang on Windows

import (
	"syscall"
	"unsafe"
)

type NETRESOURCE struct {
	Scope        uint32
	Type         uint32
	DisplayType  uint32
	Usage        uint32
	lpLocalName  *uint16
	lpRemoteName *uint16
	lpComment    *uint16
	lpProvider   *uint16
}

func MountWindowsNetworkLocation(location string, username string, password string) error {
	h := syscall.MustLoadDLL("mpr.dll")
	c := h.MustFindProc("WNetAddConnection2W")

	nr := NETRESOURCE{
		Type:         uint32(1),
                // lpLocalName: syscall.StringToUTF16Ptr("R:"), uncomment this line to map a local device
		lpRemoteName: syscall.StringToUTF16Ptr(location),
	}

	r1, _, err := c.Call(uintptr(unsafe.Pointer(&nr)),
		uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(password))),
		uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(username))), 0)

	if r1 != 0 {
		return err
	}

	return nil
}