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
+30.9k Golang : Calculate percentage change of two values
+12.8k Golang : Convert IPv4 address to packed 32-bit binary format
+13.9k Golang : Google Drive API upload and rename example
+9.3k Facebook : Getting the friends list with PHP return JSON format
+10.3k Golang : Generate random integer or float number
+7.9k Golang : What fmt.Println() can do and println() cannot do
+13.3k Golang : Count number of runes in string
+21.6k Golang : Setting up/configure AWS credentials with official aws-sdk-go
+6k Golang : Measure execution time for a function
+12.3k Elastic Search : Return all records (higher than default 10)
+30.2k Get client IP Address in Go
+11.3k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions