trap "exit 1" ERR set -euo pipefailI think for this small size of an example program the error checking in Go is pure overhead, but as soon as the program starts to have a few more functions it will be very useful to have more options than just to abort on fail (Bash trap style / set -e). So I don't have any problem with 'polluting' my source with `if err != nil` checks ;-)
What I am more concerned about are the different ways I have to call functions from different libraries like
resp, err := http.Get(url)
...
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
That is a lot more 'special' than the other function calls and the bash version and probably requires more documentation reading than '$ curl --help'. But hey, thanks to your example I have a starting point and probably are going to experiment with it in the new future.For all the others who wrote that Bash is the right tool for the job: I read your warnings, opinions and suggestions and will keep them in mind while exploring the possibilities of using Go for script like jobs.
You might be thinking "but... exceptions!". They are a pretty bad solution. The problems are:
* Error handling is hidden - it's impossible in most implementations to know which exceptions can be thrown by a function * Flow control context is lost. If you wrap lots of lines with try {} you don't know which one caused the error and can't add context information. You end up with shit error messages like "file not found" rather than "error opening config file foo.cfg: file not found". The solution is to wrap every line in a separate try/catch but that is just Go-style error handling but shitter and even more verbose.
Go is a good balance. If you want proper error handling you have to actually write it. Yes it is a little tedious but that's what it takes to do it properly.
If you don't want to do it properly then fine, use Bash and set -e. But accept that it will be shit.
The only downside really is that you have to compile the Go code, which is fast but not as fast as just interpreting a Bash script (the first time).
Another possible issue is executable size - if you have a lot of Go scripts they may take up a fair bit of space.
I wish Go had an interpreter / JIT mode for scripts.
Edit: Before someone says "but that's 3 times longer than the bash code!" please write the equivalent Bash code that has proper error checking.