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
+6.8k Golang : Output or print out JSON stream/encoded data
+19.9k Golang : Append content to a file
+18.6k Golang : Generate thumbnails from images
+14k Golang : convert rune to unicode hexadecimal value and back to rune character
+15.3k Golang : Accurate and reliable decimal calculations
+11.5k Golang : Handle API query by curl with Gorilla Queries example
+5.3k Golang : Generate Interleaved 2 inch by 5 inch barcode
+10.4k Golang : cannot assign type int to value (type uint8) in range error
+12.7k Golang : Send data to /dev/null a.k.a blackhole with ioutil.Discard
+37.7k Golang : Converting a negative number to positive number
+19.2k Golang : Check whether a network interface is up on your machine