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
+8.5k Golang : Gorilla web tool kit schema example
+5.5k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example
+7.9k Golang : Get final or effective URL with Request.URL example
+18.5k Golang : Padding data for encryption and un-padding data for decryption
+6.8k Golang : Squaring elements in array
+11k Golang : Delay or limit HTTP requests example
+10k Golang : Convert file content to Hex
+8.4k Golang : On lambda, anonymous, inline functions and function literals
+5.8k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+17.9k Golang : How to remove certain lines from a file
+6.7k Golang : constant 20013 overflows byte error message