Mastodon hachyterm.io

I am currently developing a Go REST API. I need an environment variable in my shell for the database connection string. I also need to install a Golang package for SQL migrations.

However, I do not want to pollute my machine. I hate to install the package globally just for this one use case.
Do I want to set my env variable globally? No!
But if I only set it temporarily, I need to repeat that every time.
What a hassle!

Is there a way to isolate my local dev environment?

There is!

Enter devbox and direnv!

We built Devbox to make isolated shell environments easy to learn, use, and configure. The combination of easy shell environments with Devbox, combined with convenient environment switching with Direnv makes it simple to manage multiple projects without having their setups interfere or leak into one another.

After installing both packages for MacOS, it was easy to create my environment.

  1. Run devbox init in my shell (fish shell works!)
  2. Add dependencies: devbox add go@latest golangci-lint@latest go-migrate@latest
  3. Create an .env file with my environment variiables.
  4. Run devbox generate direnv

The last command creates a pre-filled .envrc file.

# Automatically sets up your devbox environment whenever you cd into this
# directory via our direnv integration:

eval "$(devbox generate direnv --print-envrc)"

# check out https://www.jetpack.io/devbox/docs/ide_configuration/direnv/
# for more details

Add the following to the command: --env-file .env

# Automatically sets up your devbox environment whenever you cd into this
# directory via our direnv integration:

+ eval "$(devbox generate direnv --print-envrc --env-file .env)"

# check out https://www.jetpack.io/devbox/docs/ide_configuration/direnv/
# for more details

Now direnv will also read from the environment file.

I can also use the .env file in my Go program via GoDotEnv.

Now I can use my database connection string both in my shell as well as in my Go project.

Further Reading