mkdir if not exists using golang

Alfred picture Alfred · Jun 21, 2016 · Viewed 73.4k times · Source

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

Answer

Alfred picture Alfred · Jun 21, 2016

Okay I figured it out thanks to this question/answer

import(
    "os"
    "path/filepath"
)

newpath := filepath.Join(".", "public")
os.MkdirAll(newpath, os.ModePerm)

MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error.