HowtoGo
Standard Library

os

os gives platform-independent access to files, environment variables, and process state. Use ReadFile/WriteFile when a file fits comfortably in memory, and Open/Create with streaming otherwise.

Examples

Skips open/close boilerplate for small files.

err := os.WriteFile("config.json", []byte("{\"env\":\"prod\"}"), 0644)
if err != nil {
    log.Fatal(err)
}

data, err := os.ReadFile("config.json")
if err != nil {
    log.Fatal(err)
}
fmt.Println(string(data))
Output
{"env":"prod"}
FunctionDescription
Open(name string) (*File, error)
f, err := os.Open("a.txt")
Check err, then defer f.Close().
Create(name string) (*File, error)
f, err := os.Create("a.txt")
Truncates if it exists. defer f.Close().
OpenFile(name string, flag int, perm FileMode) (*File, error)
f, err := os.OpenFile(n, os.O_APPEND, 0644)
Like Open/Create, with explicit flags.
ReadFile(name string) ([]byte, error)
data, err := os.ReadFile("a.txt")
Whole file in memory. Check err first.
WriteFile(name string, data []byte, perm FileMode) error
err := os.WriteFile("a.txt", b, 0644)
Error only, the write already happened.
Stat(name string) (FileInfo, error)
info, err := os.Stat("a.txt")
info.Size(), info.IsDir() once err is nil.
Mkdir(name string, perm FileMode) error
err := os.Mkdir("logs", 0750)
Fails if the parent doesn't exist.
MkdirAll(path string, perm FileMode) error
err := os.MkdirAll("a/b/c", 0750)
Creates parents too. Safe if it exists.
Remove(name string) error
err := os.Remove("a.txt")
Deletes one file or empty dir.
RemoveAll(path string) error
err := os.RemoveAll("tmp/")
Deletes the path and everything under it.
ReadDir(name string) ([]DirEntry, error)
entries, err := os.ReadDir(".")
Range over the result, call entry.Name().
Getenv(key string) string
port := os.Getenv("PORT")
Empty string if unset. No error.
LookupEnv(key string) (string, bool)
v, ok := os.LookupEnv("PORT")
Check the bool, not the string.
Exit(code int)
os.Exit(1)
Deferred calls never run.
Args []string
name := os.Args[1]
Package var. Args[0] is the binary path.