Learning Go – Day 11

Featured image by Egon Elbre

Adding GOPATH to $PATH

  • I added $(go env GOPATH)/bin to my $PATH environment variable. For me this involved modifying my custom zsh resources.

Handling OS signals

You can use the os/signal package to listen for signal notifications sent to your process.

  • Create a channel to receive notifications on: make(chan os.Signal, 1)
  • Register to receive notifications for signals: signal.Notify()
  • Stop receiving notifications: signal.Stop()

The following example will run in an infinite loop until you either press Ctrl+C or kill the process.

package main

import (

func main() {
	fmt.Printf("Running forever until you either press Ctrl+C or `kill %d`\n", syscall.Getpid())

	sigCh := make(chan os.Signal, 1)

	signal.Notify(sigCh, syscall.SIGINT, syscall.SIGABRT)

	for {
		select {
		case recvSig := <-sigCh:
			fmt.Printf("\nReceived signal: %s\n", recvSig)
# User pressed Ctrl+C example
$ go run .
Running forever until you either press Ctrl+C or `kill 35417`
Received signal: interrupt
# Process was killed
terminal1$ go run .
Running forever until you either press Ctrl+C or `kill 35454`

terminal2$ kill 35454

signal: terminated


Cobra has become sort of a staple for writing CLIs in the golang world and it is awesome!

  • Adding Cobra as a dependency.
$ go get -u github.com/spf13/cobra@latest
  • Installing Cobra so we can use the code generation tool.
$ go install github.com/spf13/cobra-cli@latest
  • Configure the default author and license to use when generating code. Create a file ~/.cobra.yaml
author: Andre Jacobs
license: MIT
  • Starting a new Cobra based project.
$ mkdir projectSomething
$ cd projectSomething
$ go mod init projectSomething   #NOTE: not the best naming if you are going to share this

$ go get -u github.com/spf13/cobra@latest

$ cobra-cli init

$ tree
├── cmd
│   └── root.go
├── go.mod
├── go.sum
└── main.go

1 directory, 5 files
  • Note how it creates the LICENSE files and the root command underneath cmd directory.
  • Adding a new subcommand.
$ cobra-cli add buylego
$ tree
├── cmd
│   └── buylego.go
│   └── root.go
├── go.mod
├── go.sum
└── main.go
  • Adding a new subcommand to another parent command (e.g. not to root). NOTE: -p specifies the instance variable name of the command and not the command name it self.
$ cobra-cli add list -p buylegoCmd