This is the second part of a series introducing Bash programmers to Go. This part is about basics of writing CLI tools in Go. See the first part for the language building blocks.
Our first CLI tool
Bash is often used to write small CLI tools and automation. Let's start with an example CLI tool that prints "hello" to terminal. The Bash version is pretty simple:
#! /bin/bash echo hello
Now, let's implement a Go version. We start by creating a directory where the first version of our program will live. We also initialize a module in there:
$ mkdir -p hello/1 $ cd hello/1 $ go mod init hello
Since the program is not complex we don't have to think a lot about its design and can easily start with a test:
// hello/1/hello_test.go package hello_test import ( "hello" "testing" ) func TestPrintExists ( t * testing. T ) { hello . Print () }
We named the package hello_test instead of hello . This is possible and it allows for writing tests that use only the public API (identifiers starting with a capital letter) of the tested package as a real user would. In this test we just call the Print function from the hello package. Let's try and run the test:
$ go test hello: no non-test Go files in ~ /github.com/go-monk/from-bash-to-go-series/part-ii-cli-tools/hello/1 FAIL hello [build failed]
... continue reading