Golang : Check if a directory exist or not
In this short tutorial, we will learn how to check if a parameter passed as argument is directory or not. It is pretty straight forward by using the os.Stat.IsDir() function
checkdir.go
package main
import (
"os"
"flag"
"fmt"
)
func main() {
flag.Parse() // get the arguments from command line
source_dir := flag.Arg(0) // get the source directory from 1st argument
fmt.Println("Source :" + source_dir)
// check if the source dir exist
src, err := os.Stat(source_dir)
if err != nil {
panic(err)
}
// check if the source is indeed a directory or not
if !src.IsDir() {
fmt.Println("Source is not a directory")
os.Exit(1)
}
}
Hope this will be helpful.
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+11.7k Generate salted password with OpenSSL example
+15.8k Golang : Get number of CPU cores
+3.8k JavaScript : Rounding number to decimal formats to display currency
+6.8k Golang : Scan files for certain pattern and rename part of the files
+10.8k Golang : Print UTF-8 fonts on image example
+19.9k Golang : Convert string slice to struct and access with reflect example
+15.4k Golang : How to implement two-factor authentication?
+29.3k Golang : Interpolating or substituting variables in string examples
+3.6k Javascript : Access JSON data example
+18.8k Golang : Read directory content with os.Open
+8.2k Golang : Read file with ioutil
+3.8k Golang : How to pass data between controllers with JSON Web Token