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
+14.3k Golang : Convert IP version 6 address to integer or decimal number
+29.7k Golang : Saving(serializing) and reading file with GOB
+7.7k Javascript : Push notifications to browser with Push.js
+13.5k Golang : Read from buffered reader until specific number of bytes
+23k Golang : Gorilla mux routing example
+16.1k Golang : Get sub string example
+7.9k Golang : Load DSA public key from file example
+11.3k Google Maps URL parameters configuration
+9.9k Golang : Get current, epoch time and display by year, month and day
+19.8k Golang : Get current URL example
+6.9k Unix/Linux : How to fix CentOS yum duplicate glibc or device-mapper-libs dependency error?
+11.1k Golang : Create Temporary File