create a directory in go

To create a directory in Go, you can use the os.Mkdir() or os.MkdirAll() function. Here's an example using os.Mkdir():

main.go
package main

import (
    "fmt"
    "os"
)

func main() {
    // create a directory
    err := os.Mkdir("mydir", 0755)
    if err != nil {
        fmt.Println("Error creating directory:", err)
    } else {
        fmt.Println("Directory created")
    }
}
256 chars
17 lines

In this example, os.Mkdir("mydir", 0755) creates a directory named mydir with permissions 0755. If the directory already exists, an error is returned.

Alternatively, you can use os.MkdirAll() to create nested directories:

main.go
package main

import (
    "fmt"
    "os"
)

func main() {
    // create nested directories
    err := os.MkdirAll("path/to/mydir", 0755)
    if err != nil {
        fmt.Println("Error creating directory:", err)
    } else {
        fmt.Println("Directory created")
    }
}
274 chars
17 lines

In this example, os.MkdirAll("path/to/mydir", 0755) creates a directory named mydir inside a nested directory structure path/to/. If any of the directories already exist, they are not recreated. If there is an error creating any of the directories, the function returns an error.

gistlibby LogSnag