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.
Go đi kèm với một thư viện chuẩn (stdlib) toàn diện. Không giống như một số ngôn ngữ khác, stdlib của Go bao gồm công cụ cho hầu hết các tác vụ phổ biến: xử lý file, networking, JSON, HTTP, mã hóa và hơn thế nữa. Điều này có nghĩa là bạn thường không cần nhiều dependency bên ngoài để bắt đầu.
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.
Gói fmt cung cấp các hàm để định dạng và in dữ liệu. Printf là hàm phổ biến nhất, cho phép bạn sử dụng format string (tương tự C). Sprintf trả về chuỗi đã định dạng thay vì in trực tiếp. Errorf tạo lỗi từ chuỗi định dạng.
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)Format verb %v là generic và sẽ in bất kỳ giá trị nào theo cách hợp lý. %T cho bạn kiểu của giá trị, hữu ích khi debug.
The os package provides access to operating system functionality: command-line arguments, environment variables, file read/write, file open, and process control.
Gói os cung cấp quyền truy cập vào các chức năng hệ điều hành: đối số dòng lệnh, biến môi trường, đọc/ghi file, mở file và kiểm soát quy trình.
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])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.
Gói io định nghĩa interface cơ bản: Reader (đọc từ một nguồn) và Writer (ghi vào một đích). bufio cung cấp buffered reading/writing (nhanh hơn với các file lớn vì giảm các lần gọi hệ thống). bufio.Scanner hữu ích để đọc file theo dòng.
1package main23import (4 "bufio"5 "fmt"6 "io"7 "os"8 "strings"9)1011func main() {12 // io.ReadAll: read entire stream into memoryThe 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.
Gói net/http cho phép bạn xây dựng HTTP server và client. Để tạo một server đơn giản, dùng http.HandleFunc để đăng ký handler và http.ListenAndServe để bắt đầu server. Cho client, http.Get, http.Post và http.Do cho bạn các yêu cầu HTTP.
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:])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.
Gói json cung cấp json.Marshal (chuyển struct sang JSON) và json.Unmarshal (chuyển JSON sang struct). Sử dụng struct tags để ánh xạ JSON field names. json.NewEncoder/json.NewDecoder hữu ích cho streaming JSON (đọc/ghi nhiều JSON object liên tiếp).
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 emptyThe 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.
Gói strings cung cấp các hàm để làm việc với chuỗi: Contains, HasPrefix, Split, Join, TrimSpace, ReplaceAll. Gói strconv chuyển đổi giữa chuỗi và các kiểu số: Atoi (string → int), Itoa (int → string), ParseFloat, FormatFloat.
1package main23import (4 "fmt"5 "strconv"6 "strings"7)89func main() {10 // String operations11 text := "Hello, World!"12The 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.
Gói time cung cấp time.Now() để lấy thời gian hiện tại. time.Duration biểu diễn khoảng thời gian. time.Sleep dừng chương trình. time.Format định dạng thời gian (dùng reference time: Mon Jan 2 15:04:05 2006). time.Since tính thời gian trôi qua kể từ một điểm.
1package main23import (4 "fmt"5 "time"6)78func main() {9 // Current time10 now := time.Now()11 fmt.Println("Now:", now)12The 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.
Gói context cho phép bạn truyền các tín hiệu hủy và timeout giữa các goroutine. context.Background() là context gốc. context.WithTimeout tạo một context có timeout. context.WithCancel tạo một context có thể hủy bỏ. Luôn truyền context làm tham số đầu tiên trong hàm.
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 {Here is a practical example combining HTTP server, JSON, and file handling to create a simple API.
Dưới đây là một ví dụ thực tế kết hợp HTTP server, JSON, và xử lý file để tạo một API đơn giản.
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
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ì?
What does the struct tag json:"field,omitempty" do?
Struct tag json:"field,omitempty" làm gì?
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.
context.Background() returns a context that is already cancelled.
context.Background() trả về một context đã bị hủy.
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)