In this tutorial, you will learn how to add flake.nix
to a Go project.
Initialize a new project
You can start developing a Go project by simply adding main.go
and go.mod
to an empty directory. Refer to GitHub - golang-standards/project-layout: Standard Go Project Layout for a complex project layout.
Add flake.nix to the project
Initialize the template from the root directory of the project:
Terminal window nix flake init github:akirak/flake-templates#goAdd
.envrc
:Terminal window use flakeAllow direnv:
Terminal window direnv allow
Developing
Exposing the executable from the flake
To expose the program as a Nix flake package, comment out the stub inside packages
in the flake.nix
.
Adapt
pname
andversion
to match your package information:packages = eachSystem (pkgs: {default = pkgs.buildGoModule {pname = "hello";pname = "your-go-program";# Edit this if you are using a semantic versionversion = builtins.substring 0 8 (self.lastModifiedDate or "19700101");version = "0.3.4";src = self.outPath;vendorHash = lib.fakeHash;meta = { };};});Then build the package with Nix:
Terminal window nix build .#defaultIt will show an error on the hash, so update
vendorHash
to the value shown in the output.packages = eachSystem (pkgs: {default = pkgs.buildGoModule {...intensionaly omittedsrc = self.outPath;# Set the value shown from nix build- vendorHash = lib.fakeHash;+ vendorHash = "sha256-7g261Jf6Qegfz7MnNbqo3Jc5Ft33qHXvst92laOrIY0=";...};});It is also recommended to push your artifacts to a binary cache server and add its settings to the
flake.nix
:nixConfig = {extra-substituters = [# Use your cachix account"https://akirak.cachix.org"];extra-trusted-public-keys = [# Use a public key for your binary cache"akirak.cachix.org-1:WJrEMdV1dYyALkOdp/kAECVZ6nAODY5URN05ITFHC+M="];};
Creating a justfile for local workflows
You can create the following justfile
for convenience.
build: go build
run: go run main.go