Lesson 18 of 20 · Part 6: Real-world Go
A tour of the standard library
A beginner's tour of the Go standard library. Work with time, read and write files, encode and decode JSON, parse command-line flags and build a small web server.
5 min read · Updated · Beginner friendly
What you'll learn
- Work with dates, times and durations using time
- Read and write files with os and bufio
- Convert structs to and from JSON with encoding/json
- Parse command-line flags and build a tiny HTTP server
Go comes with a large, high-quality standard library. Many tasks that need third-party packages in other languages, like JSON, HTTP servers, testing and compression, are built in. You’ve already used fmt, strings, strconv, slices, maps, errors, sync and context. This lesson tours a few more packages you’ll use in almost every real program.
The full list is at pkg.go.dev/std. When you need something, check there first.
time: dates, times and durations
A time.Duration is a length of time; a time.Time is a moment. You can add durations to times, subtract times, compare them and format them:
package main
import (
"fmt"
"time"
)
func main() {
timeout := 90 * time.Second
fmt.Println("timeout:", timeout, "=", timeout.Minutes(), "minutes")
launch := time.Date(2009, time.November, 10, 15, 0, 0, 0, time.UTC)
fmt.Println("Go was announced on a", launch.Weekday())
later := launch.Add(48 * time.Hour)
fmt.Println("two days later:", later.Format("2006-01-02"))
go1 := time.Date(2012, time.March, 28, 0, 0, 0, 0, time.UTC)
days := go1.Sub(launch).Hours() / 24
fmt.Printf("Go 1.0 came %.0f days after the announcement\n", days)
fmt.Println("in order?", launch.Before(go1))
}timeout: 1m30s = 1.5 minutes
Go was announced on a Tuesday
two days later: 2009-11-12
Go 1.0 came 868 days after the announcement
in order? trueFormatting with the reference time
Go formats dates in an unusual but memorable way. Instead of codes like YYYY-MM-DD, you write how one specific moment would look. That moment is Mon Jan 2 15:04:05 MST 2006, which is easy to remember as 1 2 3 4 5 6 7: month 1, day 2, hour 3 (15), minute 4, second 5, year 6, time zone -7.
package main
import (
"fmt"
"time"
)
func main() {
t := time.Date(2026, time.July, 4, 9, 5, 0, 0, time.UTC)
fmt.Println(t.Format("2006-01-02"))
fmt.Println(t.Format("02/01/2006 15:04"))
fmt.Println(t.Format("Monday, 2 January 2006"))
fmt.Println(t.Format("3:04 PM"))
fmt.Println(t.Format(time.RFC3339))
parsed, err := time.Parse("2006-01-02", "2026-12-25")
if err != nil {
fmt.Println(err)
return
}
fmt.Println("parsed:", parsed.Weekday(), parsed.YearDay(), "day of the year")
}2026-07-04
04/07/2026 09:05
Saturday, 4 July 2026
9:05 AM
2026-07-04T09:05:00Z
parsed: Friday 359 day of the yeartime.Now() gives the current time, and time.Since(start) measures how long something took. You used both in lesson 16.
Reading and writing files
For small files, os.WriteFile and os.ReadFile do the whole job in one call:
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
path := filepath.Join(os.TempDir(), "greeting.txt")
err := os.WriteFile(path, []byte("Hello from Go!\nSecond line\n"), 0o644)
if err != nil {
fmt.Println("write failed:", err)
return
}
data, err := os.ReadFile(path)
if err != nil {
fmt.Println("read failed:", err)
return
}
fmt.Print(string(data))
fmt.Println("size:", len(data), "bytes")
os.Remove(path) // clean up
}Hello from Go!
Second line
size: 27 bytesfilepath.Joinbuilds a path with the right separator for the operating system (/or\).0o644is the file permission on Unix-like systems: the owner can read and write, everyone else can read.- Files contain bytes (
[]byte); convert withstring(data)and[]byte(text).
Line by line with bufio
For large files, or when you want to process one line at a time, open the file and read it with a bufio.Scanner:
package main
import (
"bufio"
"fmt"
"os"
"path/filepath"
"strings"
)
func main() {
path := filepath.Join(os.TempDir(), "shopping.txt")
// Create a file and write to it line by line
f, err := os.Create(path)
if err != nil {
fmt.Println(err)
return
}
for _, item := range []string{"milk", "", "bread", "coffee beans"} {
fmt.Fprintln(f, item)
}
f.Close()
// Open it again and read it line by line
f, err = os.Open(path)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
defer os.Remove(path)
scanner := bufio.NewScanner(f)
n := 0
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" {
continue // skip blank lines
}
n++
fmt.Printf("%d. %s\n", n, line)
}
if err := scanner.Err(); err != nil {
fmt.Println("read error:", err)
}
}1. milk
2. bread
3. coffee beansos.File is both an io.Reader and an io.Writer, so everything you learned in lesson 13 applies: fmt.Fprintln(f, ...) writes to a file just as it writes to the terminal.
Always close what you open
Every os.Open or os.Create should be followed by a Close. The idiom is to check the error, then immediately defer f.Close().
encoding/json
JSON is everywhere: web APIs, configuration files, logs. The encoding/json package converts between Go values and JSON. Struct tags, the text in backticks after a field, control the JSON names:
package main
import (
"encoding/json"
"fmt"
)
type Address struct {
City string `json:"city"`
Country string `json:"country"`
}
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email,omitempty"` // left out when empty
Tags []string `json:"tags"`
Address Address `json:"address"`
password string // unexported: never included in JSON
}
func main() {
u := User{
ID: 1,
Name: "Ada",
Tags: []string{"admin", "go"},
Address: Address{City: "London", Country: "UK"},
password: "secret",
}
// Go value -> JSON
data, err := json.Marshal(u)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(data))
pretty, _ := json.MarshalIndent(u.Address, "", " ")
fmt.Println(string(pretty))
}{"id":1,"name":"Ada","tags":["admin","go"],"address":{"city":"London","country":"UK"}}
{
"city": "London",
"country": "UK"
}Notice that email was left out because of omitempty, and password was never included because it’s unexported.
Going the other way, json.Unmarshal fills in a struct from JSON. Pass a pointer so it can change your variable:
package main
import (
"encoding/json"
"fmt"
)
type Product struct {
Name string `json:"name"`
Price float64 `json:"price"`
InStock bool `json:"in_stock"`
}
func main() {
input := `[
{"name": "Keyboard", "price": 49.99, "in_stock": true},
{"name": "Mouse", "price": 19.5, "in_stock": false, "color": "black"}
]`
var products []Product
if err := json.Unmarshal([]byte(input), &products); err != nil {
fmt.Println("bad JSON:", err)
return
}
for _, p := range products {
fmt.Printf("%-8s %6.2f in stock: %t\n", p.Name, p.Price, p.InStock)
}
var broken Product
err := json.Unmarshal([]byte(`{"name": "Desk", "price": "cheap"}`), &broken)
fmt.Println("error:", err)
}Keyboard 49.99 in stock: true
Mouse 19.50 in stock: false
error: json: cannot unmarshal string into Go struct field Product.price of type float64Unknown JSON fields (like "color") are ignored, and missing fields keep their zero values. When you don’t know the structure in advance, you can decode into a map[string]any, but a struct is safer and easier to work with whenever you can define one.
Generate structs from JSON
Have a big JSON sample? Paste it into the JSON to Go Struct tool to generate the matching Go types with tags.
Command-line flags
The flag package parses options like -name=Ada -times 3 for command-line tools. Each flag has a name, a default value and a help text:
package main
import (
"flag"
"fmt"
"strings"
)
func main() {
name := flag.String("name", "Gopher", "who to greet")
times := flag.Int("times", 1, "how many times to greet")
shout := flag.Bool("shout", false, "print in upper case")
flag.Parse()
msg := fmt.Sprintf("Hello, %s!", *name)
if *shout {
msg = strings.ToUpper(msg)
}
for range *times {
fmt.Println(msg)
}
fmt.Println("other arguments:", flag.Args())
}Hello, Gopher!
other arguments: []That’s the output with no flags. Try it locally with options:
go run . -name Ada -times 2 -shout extra.txtHELLO, ADA!
HELLO, ADA!
other arguments: [extra.txt]flag.String and friends return pointers, which flag.Parse fills in, so you read them with *name. Running the program with -h prints an automatically generated help message. Arguments that aren’t flags end up in flag.Args(). The raw arguments are also available in os.Args.
A tiny web server with net/http
Go’s net/http package is production-ready. Many companies run it directly on the internet without a separate web server in front. Here’s a complete server with two routes:
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /hello/{name}", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s!\n", r.PathValue("name"))
})
mux.HandleFunc("GET /api/status", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
})
log.Println("listening on http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", mux))
}Run it with go run ., then open http://localhost:8080/hello/Ada in your browser, or use curl:
curl localhost:8080/hello/Ada
curl localhost:8080/api/statusHello, Ada!
{"status":"ok"}A handler receives the request (r) and writes the response to w, an io.Writer (lesson 13 again). Patterns like "GET /hello/{name}" match the HTTP method and path, and r.PathValue("name") reads the {name} part. Every request runs in its own goroutine automatically, so the server handles many visitors at once.
Because the Playground can’t accept network connections, here’s the same handler tested entirely in memory with net/http/httptest, which is also how you’d test it for real:
package main
import (
"fmt"
"net/http"
"net/http/httptest"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /hello/{name}", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s!\n", r.PathValue("name"))
})
req := httptest.NewRequest("GET", "/hello/Grace", nil)
rec := httptest.NewRecorder() // records what the handler writes
mux.ServeHTTP(rec, req)
fmt.Println("status:", rec.Code)
fmt.Print("body: ", rec.Body.String())
rec = httptest.NewRecorder()
mux.ServeHTTP(rec, httptest.NewRequest("GET", "/nope", nil))
fmt.Println("unknown path:", rec.Code)
}status: 200
body: Hello, Grace!
unknown path: 404More packages worth knowing
| Package | Use it for |
|---|---|
bytes |
the strings functions, but for []byte |
io |
Reader/Writer helpers such as io.Copy and io.ReadAll |
log/slog |
structured logging (key/value pairs, JSON output) |
math/rand/v2 |
random numbers (rand.IntN(10)) |
crypto/rand, crypto/sha256 |
secure random bytes and hashing |
regexp |
regular expressions |
text/template, html/template |
generating text and safe HTML from templates |
os/exec |
running other programs |
embed |
bundling files (HTML, images) into your binary |
testing |
unit tests and benchmarks (next lesson) |
Exercises
1. Age in days. Using time.Date, calculate how many days old someone born on 15 August 2000 was on 1 January 2026.
Show solution
package main
import (
"fmt"
"time"
)
func main() {
born := time.Date(2000, time.August, 15, 0, 0, 0, 0, time.UTC)
day := time.Date(2026, time.January, 1, 0, 0, 0, 0, time.UTC)
fmt.Printf("%.0f days\n", day.Sub(born).Hours()/24)
}9270 days2. Config from JSON. Decode {"port": 8080, "debug": true, "admins": ["ada", "grace"]} into a Config struct and print each field.
Show solution
package main
import (
"encoding/json"
"fmt"
)
type Config struct {
Port int `json:"port"`
Debug bool `json:"debug"`
Admins []string `json:"admins"`
}
func main() {
raw := `{"port": 8080, "debug": true, "admins": ["ada", "grace"]}`
var cfg Config
if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
fmt.Println(err)
return
}
fmt.Printf("port=%d debug=%t admins=%v\n", cfg.Port, cfg.Debug, cfg.Admins)
}port=8080 debug=true admins=[ada grace]3. Count the lines. Write a file with five lines (two of them blank) to a temporary path, then read it back with a bufio.Scanner and print how many non-blank lines it has.
Show solution
package main
import (
"bufio"
"fmt"
"os"
"path/filepath"
"strings"
)
func main() {
path := filepath.Join(os.TempDir(), "lines.txt")
if err := os.WriteFile(path, []byte("one\n\ntwo\n\nthree\n"), 0o644); err != nil {
fmt.Println(err)
return
}
defer os.Remove(path)
f, err := os.Open(path)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
count := 0
scanner := bufio.NewScanner(f)
for scanner.Scan() {
if strings.TrimSpace(scanner.Text()) != "" {
count++
}
}
fmt.Println("non-blank lines:", count)
}non-blank lines: 3Recap
timehandles durations, dates and formatting with the reference time2006-01-02 15:04:05.os.ReadFile/os.WriteFilefor small files;os.Open+bufio.Scannerto read line by line; always close files.encoding/jsonconverts structs to and from JSON; struct tags set field names andomitempty.flagparses command-line options;net/httpserves the web, andhttptesttests handlers in memory.
Next, you’ll make sure your code works, and keeps working, with tests and benchmarks.
Finished this lesson?
Your progress is saved in this browser only.