golang将文件保存到桌面
I'm trying to saving files to my desktop, however whenever I run my script it saves the file in whatever directory the go script is located in.
This is the chunk of code i'm working with
func (d *downloader) downloadToFile(key string) {
// Create the directories in the path
// desktop path
desktop := "Desktop/" + d.dir
file := filepath.Join(desktop, key)
if err := os.MkdirAll(filepath.Dir(file), 0775); err != nil {
panic(err)
}
// Setup the local file
fd, err := os.Create(file)
if err != nil {
panic(err)
}
defer fd.Close()
// Download the file using the AWS SDK
fmt.Printf("Downloading s3://%s/%s to %s...
", d.bucket, key, file)
params := &s3.GetObjectInput{Bucket: &d.bucket, Key: &key}
d.Download(fd, params)
_, e := d.Download(fd, params)
if e != nil {
panic(e)
}
}
I've tried the path
desktop := "Desktop/" + d.dir
desktop := "/Desktop/" + d.dir
desktop := "Desktop/" + d.dir
desktop := "~/Desktop/ + d.dir
I can't seem to get the files to save to the desktop, for instance when i tried
desktop := "~/Desktop/ + d.dir
A directory ~
was created, inside of ~
Desktop was created, inside of Desktop the d.dir was created, and in there all the files. Again I want to run the script an no matter where I run it I want to d.dir folder with it's contents so be created on the desktop.
You can find current user profile using this function - https://godoc.org/os/user#Current
So, depending on your OS, desktop will be in corresponding folder in home directory.
something like this
myself, error := user.Current()
if error != nill {
panic(error)
}
homedir := myself.HomeDir
desktop := homedir+"/Desktop/" + d.dir
also it is worth notice, that there is a github.com/mitchellh/go-homedir
library that is a Go library for detecting the user's home directory without the use of cgo, so the library can be used in cross-compilation environments.
So using it can be better to make your program more portable.