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");
I've ran across two ways:
Check for the directory's existence and create it if it doesn't exist:
if _, err := os.Stat(path); os.IsNotExist(err) {
err := os.Mkdir(path, mode)
// TODO: handle error
}
However, this is susceptible to a race condition: the path may be created by someone else between the os.Stat
call and the os.Mkdir
call.
Attempt to create the directory and ignore any issues (ignoring the error is not recommended):
_ = os.Mkdir(path, mode)