Useful snippets of code from my day-to-day work.

Managing multiple Go versions with direnv

Install direnv

$ brew install direnv

Add to your shell

Create .envrc

GO={path to go version you want to use}
# If you use Homebrew
# GO=/opt/homebrew/Cellar/go@1.20/1.20.7/bin/go
export GOROOT="$($GO env GOROOT)"

PATH_rm '/opt/homebrew/Cellar/go*' # remove other versions
PATH_add "$($GO env GOROOT)/bin"

# use version specific GOPATH
export GOPATH=$HOME/go1.20
export PATH=$PATH:$GOPATH/bin

Allow .envrc

$ direnv allow

or allow prefix by setting up ~/.config/direnv/direnv.toml

prefix = ["{path to your workspace}"]

CAUTION: This allows execution of .envrc in all sub-directories.

Using mockery with go generate

This is a simple example of how to use mockery with go generate. It is my preferred way of generating mocks, because the mocks configuration is co-located with the interface definition.

  1. Install mockery
go install # use latest version
  1. Add a go:generate comment to your interface
//go:generate mockery -name=MyInterface -output=mocks -outpkg=mocks -case=underscore
type MyInterface interface {
  1. Run go generate
go generate ./...

Mockery -

Using xrun

Example of using xrun( to manage multiple components in a Go service.

Components can implement the xrun.Component interface or can be wrapped with xrun.ComponentFunc to be used with xrun.

# kafka consumer
consumer := newKafkaConsumer()

# gRPC server
server := newGRPCServer()

# metrics server
metrics := newMetricsServer()

err := xrun.All(