I am learning golang(beginner) and I have been searching on both google and stackoverflow but I could not find an answer so excuse me if already asked, but how can I mkdir if not exists in golang.
For example in node I would use fs-extra with the function [ensureDirSync] (if blocking is of no concern of course)
fs.ensureDir("./public");
The section of the forum Computer Advice is for people looking for advice when picking out a new computer for SketchUp. Moving your post to the Developers section.
I’m confused. How can golang be used in SketchUp, which only has APIs for Ruby and C?
2 Likes
dezmo
September 21, 2023, 1:29pm
4
I don’t see any relation to Sketchup.
Sketchup have C API and Ruby API, but no golang or Go… ?!
2 Likes
I asked the Bing AI bot and this is the reply …
Sure, here is a simple example of how you can test and create a directory if it does not exist in Go:
package main
import (
"log"
"os"
)
func main() {
dirName := "/tmp/testdir"
// check if directory exists
if _, err := os.Stat(dirName); os.IsNotExist(err) {
// create directory
errDir := os.MkdirAll(dirName, 0755)
if errDir != nil {
log.Fatal(err)
}
log.Println("Directory created")
} else {
log.Println("Directory already exists")
}
}
Copy
In this code:
os.Stat
returns the os.FileInfo
structure describing the named file. If there is an error, it will be of type *PathError
.
os.IsNotExist
is a function that checks whether the error is indicating that a file or directory does not exist.
os.MkdirAll
creates a directory named path, along with any necessary parents, and returns nil, or else it returns an error. The permission bits perm
(e.g., 0755
) are used for all directories that the function creates.
log.Fatal
is equivalent to log.Print()
followed by a call to os.Exit(1)
.
log.Println
calls Output
to print to the standard logger. Arguments are handled in the manner of fmt.Println
.
Remember to replace "/tmp/testdir"
with the path of the directory you want to create. This code will create the directory if it does not exist, and do nothing if the directory already exists. It will also print a message to the console indicating whether the directory was created or if it already exists. If there is an error creating the directory, the program will exit with a status code of 1 and print the error to the console.
Please note that you need to have the necessary permissions to create a directory in the specified path. If you do not have the necessary permissions, the os.MkdirAll
function will return an error.
I hope this helps! Let me know if you have any other questions. Happy coding!