Skip to content

Chapter 6 of 7

Standard Library: I/O, Encoding, Web, and Time

Go's I/O model centers on two interfaces: io.Reader with Read(p []byte) (n int, err error) and io.Writer with Write(p []byte) (n int, err error). Files, network connections, buffers, and HTTP bodies all satisfy them, allowing uniform streaming code. io.Copy(dst, src) is the idiomatic way to pump data between any reader and writer using an internal buffer, while io.ReadAll(r) slurps an entire io.Reader into memory. The bufio package adds buffering on top: bufio.NewReader reduces syscall frequency for reads, bufio.NewWriter batches writes that should be flushed before the writer is closed, and bufio.Scanner provides a convenient line-by-line interface. File I/O is similarly straightforward with os.ReadFile and os.WriteFile for whole-file operations, and os.Create combined with file Write methods for streaming writes. Cross-platform path manipulation is handled by path/filepath (OS-aware with filepath.Join and filepath.Separator), while the path package works on slash-separated paths suitable for URLs.

The encoding packages give Go strong support for structured data. encoding/json is the most widely used: json.Marshal converts a value to []byte, json.Unmarshal parses a byte slice into a struct, while json.NewEncoder and json.NewDecoder stream JSON through an io.Writer or io.Reader. Struct tags such as json:"name,omitempty" control field naming and behavior, json:"-" excludes a field, and dec.DisallowUnknownFields() enforces strict decoding. The companion packages encoding/binary, encoding/hex, and encoding/base64 cover fixed-width binary I/O with endianness control, hexadecimal encoding, and base64 variants for safe transport (URL-safe URLEncoding and unpadded RawURLEncoding for tight formats). The strings package provides additional utilities such as strings.Repeat and strings.SplitN, while strings.Builder avoids the O(n²) cost of repeated concatenation.

Go's standard library makes it trivial to stand up an HTTP service. A handler implements http.Handler with ServeHTTP(http.ResponseWriter, *http.Request), while http.HandlerFunc adapts a plain function to that interface. http.NewServeMux builds a request router, and http.ListenAndServe starts the server; for production use, construct an &http.Server with explicit timeouts. Headers must be set on w.Header() before any body is written or w.WriteHeader(code) is called, since they become immutable once the response starts. The client side offers http.Get for simple calls and http.NewRequest combined with client.Do(req) for fully customized requests, with defer resp.Body.Close() and full-body reads being essential to avoid connection leaks. Time handling is provided by time.Time (an instant with nanosecond precision), time.Duration (an int64 alias for nanoseconds, with constants like time.Second and time.Hour), and the reference layout "Mon Jan 2 15:04:05 MST 2006" used by Format and Parse. The context package ties everything together: context.WithTimeout and context.WithCancel create cancellable contexts that propagate deadlines and cancellation through function calls and HTTP requests, allowing long-running goroutines to be shut down cleanly.

All chapters
  1. 1Language Fundamentals and Project Structure
  2. 2Composite Types and Data Structures
  3. 3Functions, Methods, and Interfaces
  4. 4Error Handling, defer, and Formatting
  5. 5Concurrency
  6. 6Standard Library: I/O, Encoding, Web, and Time
  7. 7Testing, Tooling, and Runtime Internals

Drill it

Reading is not remembering. These come from the Go Programming deck:

Q

What is Go (Golang)?

Go is an open-source programming language developed at Google by Robert Griesemer, Rob Pike, and Ken Thompson. It is statically typed, compiled, and designed fo...

Q

How do you declare a variable in Go?

You can declare variables using:var x int = 10var y = "hello" (type inferred)z := 42 (short declaration, only inside functions)

Q

What is a goroutine?

A goroutine is a lightweight thread managed by the Go runtime. You start one with the go keyword:go myFunction()Goroutines are multiplexed onto OS threads and a...

Q

How do you create a channel in Go?

Use the make function:ch := make(chan int) — unbufferedch := make(chan string, 5) — buffered with capacity 5Channels are used to communicate between goroutines...