Reputation: 25984
I can not understand, why I am not able to create a folder and write to a file, and then read it in again - with the same path in same func, just for testing?
When I run "go test myio_test.go" on the file. I get
myio_test.go
...
func TestMyIo(t *testing.T) {
myio.CreateTempJsonFile()
}
....
myio.go
package myio
import (
"fmt"
"io/ioutil"
"path"
//"syscall"
// "os"
"bitbucket.org/kardianos/osext"
"os"
)
func CreateTempJsonFile() {
exePath, _ := osext.Executable()
filePath := path.Dir(exePath + "/json/")
fmt.Println("create: ", filePath)
_, errx := os.Stat(filePath)
if os.IsNotExist(errx) {
errm := os.Mkdir(filePath, 0644)
if errm != nil {
fmt.Println("error creating dir...")
panic(errm)
}
}
writeError := ioutil.WriteFile(filePath+"/user.txt", []byte(`{"user": "Mac"}`), 0644) // os.ModeTemporary)// 0644)
if writeError == nil {
fmt.Println("Ok write")
} else {
fmt.Println("Error write")
}
_, err := ioutil.ReadFile(filePath + "/user.txt")
if err == nil {
fmt.Println("Reading file")
} else {
fmt.Println("Error reading file")
}
}
It is like the os.Stat(filePath) thinks the folder is already there. If I then remove the check for os.Stat() and just go and create the folder I get a panic "not a directory "?
fmt.Println("create: ", filePath) prints:
/private/var/folders/yj/jcyhsxxj6ml3tdfkp9gd2wpr0000gq/T/go-build627785093/command-line-arguments/_test/myio.test/json
It is all strange, as each test creates a new "/go-buildxxx/" folder and therefore the folder should never actually be there?
Any ideas?
Upvotes: 1
Views: 1932
Reputation: 109432
First, you need to split off the executable from it's base path as it's returned from osext
exePath, _ := osext.Executable()
base, _ := filepath.Split(exePath)
(or use osext.ExecutableFolder()
)
Then you need to create the directory with the permissions 0755
. Directories need the executable bit set in order to traverse them.
Upvotes: 2