Tips

Go

Useful GoLang tips.

References

Point to Local

While refactoring and troubleshooting code it is sometimes necessary to point to the local version of a package.

You can do this by modifying the go.mod file as follows:

require (
    github.com/queone/utl v1.0.0
)

replace github.com/queone/utl => /Users/myuser/mycode/utl

Build Issues

  1. If you get:
    $ go build
    go: go.mod file not found in current directory or any parent directory; see 'go help modules'
    

    Try this

    go mod init <package_name>   # For example, this would be 'zls' for github.com/git719/zls
    go mod tidy
    
  2. If you get incompatible modules, try go clean -modcache
  3. You may also want to install staticcheck and run:
    go vet ./...
    staticcheck ./...
    

    This will check for common code issues.

Install Go

Use the install-golang.sh BASH script

  1. curl -LO https://raw.githubusercontent.com/git719/tools/main/bash/install-golang.sh to download the script
  2. ./install-golang.sh 1.22.0 to install GoLang version 1.22.0
  3. Above tries to install at $HOME/go, so if you have a previous version there you will first need to back that up
  4. Finally, set GOPATH variable to ~/go; add it in your PATH; and also add $GOPATH/bin to it

This script can be used to install Go on:

Reduce Binary Executable Size

To reduce binary executable sizes:

  1. Always compile with -ldflags "-s -w"
  2. And use UPX:
    brew install upx
    upx -9 <binary>
    

Useful Code Snippets

Common Makefile

Makefiles are usually not needed with Go, but if you must, this one for macOS and Linux will build target binaries for multiple OSes.

# Makefile
# Assumes GOPATH is already set up properly, e.g., $HOME/go

default:
  GOOS=darwin GOARCH=amd64 go build -ldflags "-s -w" -o build/macos/awsinfo
all:
  rm -rf build
  mkdir -p build/{macos,centos,windows}
  go get -u github.com/aws/aws-sdk-go/...
  go get -u github.com/vaughan0/go-ini
  GOOS=darwin GOARCH=amd64 go build -ldflags "-s -w" -o build/macos/awsinfo
  GOOS=linux GOARCH=amd64 go build -ldflags "-s -w" -o build/centos/awsinfo
  GOOS=windows GOARCH=amd64 go build -ldflags "-s -w" -o build/windows/awsinfo.exe

# Modify below target to where you keep your binaries
install:
  cp build/macos/awsinfo $(HOME)/data/bin
clean:
  rm -rf build