Skip to content
Skip to content
DocsGo LearningexpertStandard Library
Chapter 11 of 14·expert·12 min read

Standard Library

Thư Viện Chuẩn

fmt, os, net/http, encoding/json, context, and more

Hover or tap any paragraph to see Vietnamese translation

Go Standard Library

Go ships with a comprehensive standard library. Unlike some languages, Go's stdlib includes tools for most common tasks: file handling, networking, JSON, HTTP, encoding, and more. This means you often do not need many external dependencies to get started.

fmt — Formatting and Printing

The fmt package provides functions for formatting and printing data. Printf is the most common function, allowing you to use format strings (similar to C). Sprintf returns a formatted string instead of printing. Errorf creates an error from a format string.

main.go
1package main23import (4	"fmt"5)67func main() {8	// Printf: print with format string9	name := "Alice"10	age := 3011	score := 95.512	fmt.Printf("Name: %s, Age: %d, Score: %.1f\n", name, age, score)
Tip
The format verb %v is generic and prints any value in a reasonable way. %T gives you the type of a value, useful when debugging.

os — System Interaction

The os package provides access to operating system functionality: command-line arguments, environment variables, file read/write, file open, and process control.

main.go
1package main23import (4	"fmt"5	"os"6)78func main() {9	// os.Args: command-line arguments (os.Args[0] is program name)10	fmt.Println("Program name:", os.Args[0])11	if len(os.Args) > 1 {12		fmt.Println("First argument:", os.Args[1])

io and bufio — Stream Reading and Writing

The io package defines basic interfaces: Reader (read from a source) and Writer (write to a destination). bufio provides buffered reading/writing (faster with large files by reducing system calls). bufio.Scanner is useful for reading files line by line.

main.go
1package main23import (4	"bufio"5	"fmt"6	"io"7	"os"8	"strings"9)1011func main() {12	// io.ReadAll: read entire stream into memory

net/http — HTTP Client and Server

The net/http package lets you build HTTP servers and clients. To create a simple server, use http.HandleFunc to register handlers and http.ListenAndServe to start. For clients, http.Get, http.Post, and http.Do give you HTTP requests.

main.go
1package main23import (4	"fmt"5	"io"6	"net/http"7)89// HTTP Server10func helloHandler(w http.ResponseWriter, r *http.Request) {11	w.Header().Set("Content-Type", "text/plain")12	fmt.Fprintf(w, "Hello, %s!\n", r.URL.Path[1:])

encoding/json — JSON Marshal/Unmarshal

The json package provides json.Marshal (struct to JSON) and json.Unmarshal (JSON to struct). Use struct tags to map JSON field names. json.NewEncoder/json.NewDecoder are useful for streaming JSON.

main.go
1package main23import (4	"encoding/json"5	"fmt"6	"log"7)89type User struct {10	Name    string `json:"name"`11	Age     int    `json:"age"`12	Email   string `json:"email,omitempty"`  // omitted if empty

strings and strconv — String Manipulation

The strings package provides functions for string operations: Contains, HasPrefix, Split, Join, TrimSpace, ReplaceAll. The strconv package converts between strings and numeric types: Atoi, Itoa, ParseFloat, FormatFloat.

main.go
1package main23import (4	"fmt"5	"strconv"6	"strings"7)89func main() {10	// String operations11	text := "Hello, World!"12

time — Time and Duration

The time package provides time.Now() to get current time. time.Duration represents a time interval. time.Sleep pauses the program. time.Format formats time using a reference time: Mon Jan 2 15:04:05 2006. time.Since calculates elapsed time.

main.go
1package main23import (4	"fmt"5	"time"6)78func main() {9	// Current time10	now := time.Now()11	fmt.Println("Now:", now)12

context — Cancellation and Timeouts

The context package lets you pass cancellation and timeout signals between goroutines. context.Background() is the root context. context.WithTimeout creates a context with a timeout. context.WithCancel creates a cancellable context. Always pass context as the first parameter.

main.go
1package main23import (4	"context"5	"fmt"6	"time"7)89// Function that respects context10func doWork(ctx context.Context, workName string) {11	for i := 1; i <= 5; i++ {12		select {

HTTP Server + JSON — Combined Example

Here is a practical example combining HTTP server, JSON, and file handling to create a simple API.

main.go
1package main23import (4	"encoding/json"5	"fmt"6	"net/http"7)89type Product struct {10	ID    int    `json:"id"`11	Name  string `json:"name"`12	Price float64 `json:"price"`

Key Takeaways

Điểm Chính

  • fmt.Printf uses format verbs like %v, %T, %d, %s for outputfmt.Printf sử dụng các format verb như %v, %T, %d, %s để in
  • io.Reader and io.Writer are fundamental interfaces for streaming dataio.Reader và io.Writer là các interface cơ bản để streaming dữ liệu
  • json.Marshal/Unmarshal converts between Go structs and JSON using struct tagsjson.Marshal/Unmarshal chuyển đổi giữa struct Go và JSON sử dụng struct tags
  • context allows passing cancellation and timeout signals through function callscontext cho phép truyền tín hiệu hủy và timeout qua các lệnh gọi hàm

Practice

Test your understanding of this chapter

Quiz

When using json.Unmarshal to parse JSON into a Go struct, what must the target parameter be?

Khi sử dụng json.Unmarshal để phân tích JSON thành struct Go, tham số đích phải là gì?

Quiz

What does the struct tag json:"field,omitempty" do?

Struct tag json:"field,omitempty" làm gì?

True or False

bufio.Scanner is less efficient than io.ReadAll for reading large files because it reads line by line.

bufio.Scanner kém hiệu quả hơn io.ReadAll khi đọc các file lớn vì nó đọc từng dòng.

True or False

context.Background() returns a context that is already cancelled.

context.Background() trả về một context đã bị hủy.

Code Challenge

Fill in the format verb to print the type of a value

Điền vào format verb để in kiểu của một giá trị

fmt.Printf("% is of type %", 42, 42)
Built: 6/25/2026, 3:03:36 PM