4. Go Environment

Let's clear up a few points before you start writing Go locally.

Directory Structure

To recap how packages and modules work in your project directory structure:

  • You will have many git repositories on your machine (typically one per project).

  • Each repository is typically a single module.

  • Each module contains one or more packages.

  • Each package consists of one or more Go source files in a single directory.

The path to a package's directory determines its import path and where it can be downloaded from if you decide to host it on a remote version control system like GitHubarrow-up-right or GitLabarrow-up-right.

A Note About GOPATH

circle-exclamation

Get Into Your Workspace

Navigate to a location on your machine where you want to store some code. For example, one approach is to store all code in ~/workspace, then organize it into subfolders based on the remote location. For example:

~/workspace/github.com/wagslane/go-password-validator = https://github.com/wagslane/go-password-validator

That said, you can put your code wherever you want.

Directory Organization Hierarchy

Typical Setup

Your workspace structure:

Organizing by Remote Location

Mirror the remote URL structure locally:

Remote:

Local:

Benefits:

  • Easy to find projects

  • Matches import paths

  • Organized by source

GOPATH - Ignore It

Old way (deprecated):

New way (modules):

Key point: Avoid $GOPATH/src directory. Work anywhere else on your machine.

What is GOPATH?

  • Environment variable (usually ~/go)

  • Used in old Go versions (pre-modules)

  • You don't need to set it or use it

  • Modern Go modules work anywhere

Setting Up a Project

Create project directory

Initialize module

{% endstep %}

{% step %}

Write code

{% endstep %} {% endstepper %}

Example: Real Project Structure

Import paths match directory structure:

Where to Put Your Code

Option 1: Mirror remote (recommended)

Option 2: Flat structure

Option 3: Whatever you want

All work with Go modules β€” the location doesn't matter anymore.

Quick Reference

Concept
Example
Notes

Workspace

~/workspace

Where you store code

Repository

~/workspace/github.com/user/project

One project

Module

go.mod in repo root

Defined by go.mod

Package

customer/ subdirectory

Directory with .go files

GOPATH

~/go

Ignore it, don't use it

Commands to Get Started

Key Takeaways

  1. Work anywhere β€” modules work in any directory

  2. Avoid GOPATH/src β€” that's the old way

  3. Mirror remote structure β€” optional but organized

  4. One repo = one module β€” typical setup

  5. go.mod defines module β€” always at repo root

  6. Subdirectories = packages β€” each directory is a package

Bottom line: Put your code anywhere outside $GOPATH/src, initialize with go mod init, and you're good to go!