0Pricing
Go Academy · Lesson

Internal Packages and Workspaces

internal/, replace directives, go work

The internal/ Directory

Packages inside an internal/ directory can only be imported by code in the parent directory tree. This enforces package encapsulation:

// Project structure:
// myapp/
//   main.go
//   internal/
//     auth/auth.go      <- can only be imported by myapp/
//     db/db.go          <- can only be imported by myapp/
//   api/
//     handlers.go       <- can import myapp/internal/auth

// External package CANNOT do:
// import "myapp/internal/auth"  <- compile error

Using internal/ Packages

Code within the same module (above the internal/ directory) can freely import internal packages:

// myapp/api/handlers.go
package api

import (
    "myapp/internal/auth"
    "myapp/internal/db"
)

func GetUser(id int) (*db.User, error) {
    if !auth.IsValid() {
        return nil, auth.ErrUnauthorized
    }
    return db.FindUser(id)
}

All lessons in this course

  1. Packages: Organizing Go Code
  2. Go Modules with go mod
  3. Adding External Dependencies
  4. Internal Packages and Workspaces
← Back to Go Academy