mkdir if not exists using golang Ask Question

mkdir if not exists using golang Ask Question

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");

ベストアンサー1

Okay I figured it out thanks to this question/answer

import(
    "os"
    "path/filepath"
)

newpath := filepath.Join(".", "public")
err := os.MkdirAll(newpath, os.ModePerm)
// TODO: handle error

Relevant Go doc for MkdirAll:

MkdirAll必要な親とともに path という名前のディレクトリを作成し、nil を返すか、エラーを返します。

...

パスがすでにディレクトリである場合、MkdirAll は何も行わず、nil を返します。

おすすめ記事