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
+16.3k Golang : Find IP address from string
+8.3k Golang : Identifying Golang HTTP client request
+5.4k Unix/Linux : How to fix CentOS yum duplicate glibc or device-mapper-libs dependency error?
+9.1k Golang : Get UDP client IP address and differentiate clients by port number
+16.7k Golang : Logging with logrus
+12.3k Android Studio : Use image as AlertDialog title with custom layout example
+17.3k Golang : Fix cannot download, $GOPATH not set error
+4.1k Golang : Issue HTTP commands to server and port example
+8k Golang : Get all countries currencies code in JSON format
+27.5k Golang : How to verify uploaded file is image or allowed file types
+7.4k Golang : Capture text return from exec function example
+9.2k Golang : Fix - does not implement sort.Interface (missing Len method)