How to create a directory with GO

Introduction

In this brief tutorial we are going to use the "os" package to create a new directory with GO language. To make the directory path compatible with all OS we will also use the "path" package. We will use the home directory to make the tutorial a little more interesting.

Step 1:

Create a file named "main.go" with the following contents:

package main

import (
   "fmt"
   "os"
   "os/user"
   "path/filepath"
)

func check(e error) {
    if e != nil {
        panic(e)
    }
}

func main() {
   usr, err := user.Current()
   check(err)
   // filepath.Separator is used to maintain path compatibility on many OSes.
   path := usr.HomeDir + string(filepath.Separator) + ".goprojectconfig"
   // we print the directory we are going to create
   fmt.Println(path)
   os.Mkdir(path, 0777)
 }

Leonardo Lazzaro

Software engineer and technical writer. 10+ years experience in DevOps, Python, and Linux systems.

More articles by Leonardo Lazzaro