I am writing a CLI interface program in Go.my program requires a user to enter a filename as an argument . following is the code I wrote to handle the situations in which user doesn't enter any argument . but it panics and gives an error "index out of range".how do I handle this?
package main
import (
"encoding/hex"
"fmt"
"io/ioutil"
"log"
"os"
)
func main() {
if len(os.Args) == 0 {
fmt.Println("usage: gohex <filename>")
os.Exit(1)
} else {
filename := os.Args[1]
data, err := ioutil.ReadFile(filename)
if err != nil {
log.Fatal(err)
}
fmt.Println(hex.Dump(data))
}
}
Your problem relies in this line:
if len(os.Args) == 0
You are checking for the first argument which as you supposed should be the filename, but in fact is the go / executable filename. So if you wish to check if an argument has been provided you need to check that the argument length is greater than 1
. Change the code to:
if len(os.Args) <= 1 {
log.Fatal("usage: gohex <filename>")
}
The other answer has a couple of issues. It has this check:
len(os.Args) <= 1
but len(os.Args)
must always be at least 1
, so using <=
is pointless.
Further, in this specific case, len
of anything other than 2
is invalid as
well. So just check that:
package main
import "os"
func main() {
if len(os.Args) != 2 {
println("gohex <filename>")
return
}
filename := os.Args[1]
println(filename)
}
Side note, personally I also think using os.Exit(1)
is invalid in this context
as well. I think "printing the help text" is a valid use case, and not an error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With