Snippets

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

https://direnv.net/docs/hook.html

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

[whitelist]
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 github.com/vektra/mockery/v2@2.23.4 # 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 {
    DoSomething()
}
  1. Run go generate
go generate ./...

Mockery - https://vektra.github.io/mockery/latest/

Using xrun

Example of using xrun(https://github.com/gojekfarm/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(
    xrun.NoTimeout,
    consumer,
    server,
    metrics,
)

Blog: https://ajatprabha.in/2023/05/24/intro-xrun-package-managing-component-lifecycle-go