mkdir if not exists using golang

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

Solution 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 creates a directory named path, along with any necessary parents, and returns nil, or else returns an error.

...

If path is already a directory, MkdirAll does nothing and returns nil.

Solution 2:

I've ran across two ways:

  1. 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.

  1. Attempt to create the directory and ignore any issues (ignoring the error is not recommended):

    _ = os.Mkdir(path, mode)