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
+18k Golang : Populate dropdown with html/template example
+11k Golang : Perform sanity checks on filename example
+8.5k Golang : Detect Pascal, Kebab, Screaming Snake and Camel cases
+22.3k Find and replace a character in a string in Go
+20.9k Golang : Join arrays or slices example
+5.3k Golang : Experimenting with the Rejang script
+11.7k Swift : Convert (cast) Int or int32 value to CGFloat
+13.8k Golang : Save(pipe) HTTP response into a file
+10.1k Golang : Web routing/multiplex example
+12.7k Golang : Convert spaces to tabs and back to spaces example