Sling Academy
Home/Golang/Securely Storing Secrets with Environment Variables in Go

Securely Storing Secrets with Environment Variables in Go

Last updated: November 27, 2024

In software development, handling sensitive information like API keys, database credentials, and other secrets is crucial for application security. Using environment variables is one of the best practices for managing these secrets safely. This article will guide you through securely storing and accessing secrets with environment variables in a Go application.

Why Use Environment Variables?

Environment variables offer a simple and effective way to separate sensitive data from your codebase. This means you don't have to hard-code secrets directly in your code, which helps to maintain security when sharing code or deploying applications.

Setting Environment Variables

Environment variables can be set in several ways:

  • Directly in the terminal for a session
  • Using a .env file
  • In the configuration of your cloud or container service

Terminal Session

You can set an environment variable for your terminal session directly:

export API_KEY="your_api_key_here"

However, this will only persist for the current session.

Using a .env File

Create a .env file in your project directory and add your variables:

API_KEY=your_api_key_here
DB_PASSWORD=your_db_password_here

Ensure your .env file is added to .gitignore to prevent pushing it to version control.

Loading Environment Variables in Go

To access these variables in your Go application, you'd typically use the os package. Alternatively, for .env files, you might use a package like godotenv.

Using the os Package

package main

import (
  "fmt"
  "os"
)

func main() {
  apiKey := os.Getenv("API_KEY")
  if apiKey == "" {
    fmt.Println("API_KEY environment variable not set!")
    return
  }
  fmt.Println("API Key:", apiKey)
}

In this code snippet, os.Getenv is used to retrieve the value of API_KEY. If the key is not set, it prints a warning message.

Using the godotenv Package

The godotenv package can be used to load environment variables from a .env file into your application. First, you need to install the package:

go get github.com/joho/godotenv

Here is how you can use it:

package main

import (
  "fmt"
  "log"
  "github.com/joho/godotenv"
  "os"
)

func main() {
  err := godotenv.Load()
  if err != nil {
    log.Fatal("Error loading .env file")
  }

  apiKey := os.Getenv("API_KEY")
  if apiKey == "" {
    fmt.Println("API_KEY environment variable not set!")
    return
  }
  fmt.Println("API Key:", apiKey)
}

This script loads environment variables from a .env file, printing an error and exiting if the file is not found or cannot be read.

Best Practices

  • Keep your .env files and any files with sensitive information out of version control.
  • Use encryption or secret management services in production environments.
  • Regularly rotate your keys and credentials.
  • Avoid logging sensitive information.

By following these practices, you can significantly enhance the security of your applications and protect user data.

Next Article: Encrypting Streams with `io.Reader` and `io.Writer` in Go

Previous Article: Building a Secure Hash Table with HMAC in Go

Series: Cryptography and Security in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant