0Pricing
Go Academy · Lesson

os and filepath Packages

Environment variables, paths, and OS interaction

os.Args — Command-Line Arguments

os.Args holds the command-line arguments. os.Args[0] is the program name:

package main
import ("fmt"; "os")

func main() {
    fmt.Println("Program:", os.Args[0])
    if len(os.Args) < 2 {
        fmt.Println("Usage: program <name>")
        os.Exit(1)
    }
    fmt.Printf("Hello, %s!\n", os.Args[1])
}

os.Getenv and os.Setenv

Read and write environment variables:

package main
import ("fmt"; "os")

func main() {
    // Read env var (returns "" if not set)
    home := os.Getenv("HOME")
    fmt.Println("HOME:", home)

    // Set env var
    os.Setenv("APP_ENV", "production")
    fmt.Println(os.Getenv("APP_ENV")) // production

    // Get with default pattern:
    port := os.Getenv("PORT")
    if port == "" { port = "8080" }
    fmt.Println("Port:", port)
}

All lessons in this course

  1. fmt and strings Packages
  2. strconv, math and sort
  3. time Package Essentials
  4. os and filepath Packages
← Back to Go Academy