Go📦Standard Libraryintermediate
os — Operating System Interface
Go · Standard Library · Run with go run
Explanation
The `os` package provides OS-level operations: file I/O, environment variables, process control, and working directory. `os.Open` opens for reading; `os.Create` opens for writing (truncating). `os.ReadFile` and `os.WriteFile` are convenience wrappers for small files. `os.Args` holds command-line arguments; `os.Getenv` reads environment variables.
Real-World Scenario
Reading a config file at startup: `data, err := os.ReadFile("/etc/myapp/config.json")`. If `MYAPP_CONFIG` env var is set, use that path: `path := os.Getenv("MYAPP_CONFIG")`.
Quick Snippet
snippet.go
import "os"
// Read entire small file
data, err := os.ReadFile("config.json")
// Write file (creates or truncates)
err = os.WriteFile("output.txt", []byte("hello\n"), 0644)
// Open for streaming large file
f, err := os.Open("large.bin")
if err != nil { log.Fatal(err) }
defer f.Close()
// Environment
home := os.Getenv("HOME")
port, ok := os.LookupEnv("PORT") // distinguish missing vs empty
// Exit with status code
os.Exit(1)Full Example
os_basics.go
// Compile: go run os_basics.go
// Output:
// wrote and read: hello from os
// PATH is set: true
// args count >= 1: true
package main
import (
"fmt"
"os"
)
func main() {
const path = "os_demo.txt"
// Write then read a small file
if err := os.WriteFile(path, []byte("hello from os"), 0644); err != nil {
fmt.Println("write error:", err)
return
}
defer os.Remove(path)
data, err := os.ReadFile(path)
if err != nil {
fmt.Println("read error:", err)
return
}
fmt.Println("wrote and read:", string(data))
// Environment variables
_, ok := os.LookupEnv("PATH")
fmt.Println("PATH is set:", ok)
fmt.Println("args count >= 1:", len(os.Args) >= 1)
}
Run command
go run os_basics.go