Go comes with an integrated toolchain for formatting, linting, testing, building, and deployment. No complex configuration needed -> these tools work out of the box. This creates a consistent development experience and reduces configuration decisions.
Go đi kèm với một bộ công cụ tích hợp sẵn cho formatting, linting, testing, building và deployment. Không cần cấu hình phức tạp — các công cụ này hoạt động ngay từ hộp. Điều này tạo ra một trải nghiệm phát triển nhất quán và giảm quyết định cấu hình.
go fmt automatically formats Go code according to standard Go style. No debates about rules -> the tool decides. Gofmt is the underlying tool; go fmt is a convenient wrapper. Run go fmt ./... to format your entire project.
go fmt tự động định dạng code Go theo standard Go style. Không có tranh cãi về quy tắc — công cụ quyết định. Gofmt là công cụ cơ bản; go fmt là wrapper tiện dụng. Chạy go fmt ./... để định dạng toàn bộ dự án.
1// Unformatted code2func Add(a,b int)int{3return a+b4}56// After 'go fmt':7func Add(a, b int) int {8 return a + b9}1011// Run formatting12go fmt ./... // format all packages13gofmt -w main.go // format and write to file14gofmt -l ./... // list files that need formattingĐa số IDE/editor Go tích hợp go fmt và chạy tự động khi bạn lưu file. Điều này làm cho bạn không bao giờ phải lo lắng về việc chạy nó thủ công.
go vet checks code for common errors the compiler misses: incorrect Printf format verb usage, unreachable code, common mistake patterns. Run go vet ./... frequently, especially before committing.
go vet kiểm tra code cho các lỗi phổ biến mà trình biên dịch không bắt: việc sử dụng sai format verb trong Printf, code không thể truy cập được, các mẫu lỗi thường gặp. Chạy go vet ./... thường xuyên, nhất là trước khi commit.
1// Bad code that vet catches2package main34import "fmt"56func main() {7 // Wrong format verb for string8 name := "Alice"9 fmt.Printf("%d\n", name) // vet warns: %d expects int1011 // Unreachable code12 if true {go test finds and runs all test functions in *_test.go files. Important flags: -v (verbose), -run (filter tests), -race (detect data races), -bench (run benchmarks), -cover (code coverage).
go test tìm và chạy tất cả các hàm test trong *_test.go files. Các flag quan trọng: -v (verbose), -run (filter test), -race (detect data races), -bench (run benchmarks), -cover (code coverage).
1// Run tests2go test ./... // test all packages3go test -v ./... // verbose output45// Filter tests6go test -run TestAdd ./... // run tests matching 'TestAdd'7go test -run TestAdd/positive ./... // run TestAdd/positive subtest89// Race detection10go test -race ./... // detect concurrent access to shared memory1112// Benchmarksgo build compiles code to a binary without installing. go install compiles and saves the binary to $GOBIN. Use GOOS and GOARCH env vars to cross-compile for other platforms. Flags like -ldflags let you inject version/build info.
go build biên dịch code thành binary mà không cài đặt. go install biên dịch và lưu binary vào $GOBIN. Sử dụng GOOS và GOARCH env vars để cross-compile cho các nền tảng khác. Các flag như -ldflags cho phép injected version/build info.
1// Build2go build ./... // build all packages3go build -o myapp ./cmd/app // build with specific output name4go build -o . ./... // build all packages in current dir56// Install (binary goes to $GOBIN)7go install ./... // install all packages8go install ./cmd/app // install specific package910// Cross-compilation11GOOS=linux GOARCH=amd64 go build ./... // Linux 64-bit12GOOS=darwin GOARCH=arm64 go build ./... // macOS ARM (M1)Cross-compilation trong Go rất dễ vì không có C dependencies mặc định. Bạn có thể biên dịch cho Linux từ macOS hoặc Windows mà không cần bất kỳ setup đặc biệt.
go mod manages your project's dependencies. The go.mod file stores dependencies and their versions. go mod tidy adds missing dependencies and removes unused ones. go mod vendor copies dependencies into vendor/. go mod graph displays the dependency tree.
go mod quản lý dependency của dự án. Tệp go.mod lưu trữ các dependency và phiên bản của chúng. go mod tidy thêm các dependency bị thiếu và xóa các dependency không sử dụng. go mod vendor sao chép dependency vào thư mục vendor/. go mod graph hiển thị dependency tree.
1// Initialize module2go mod init github.com/user/myapp34// Add dependency (automatic when used in code)5go get github.com/gorilla/mux@v1.8.06go get github.com/lib/pq // latest version78// Update dependencies9go mod tidy // add missing, remove unused10go mod tidy -v // verbose1112// Vendor dependencies (copy to vendor/)golangci-lint is an aggregator of linters. Instead of running linters separately, golangci-lint runs them all at once. Configure via .golangci.yml. Popular linters: errcheck (unchecked errors), staticcheck (bug detection), gosimple (code simplification).
golangci-lint là tập hợp các linter. Thay vì chạy linter riêng biệt, golangci-lint chạy tất cả cùng một lúc. Cấu hình bằng .golangci.yml. Các linter phổ biến: errcheck (unchecked errors), staticcheck (bug detection), gosimple (code simplification).
1// Install golangci-lint2curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin34// Run all linters5golangci-lint run ./...67// Run specific linter8golangci-lint run --disable-all -E errcheck ./...910// Fix issues (if possible)11golangci-lint run --fix ./...12Directives //go:generate let you run tools to generate code. Use cases: stringer (generate String() method), protobuf (generate from .proto files), mockery (generate mocks). Run go generate ./... to execute all directives.
Directives //go:generate cho phép bạn chạy tool để sinh code. Các use case: stringer (sinh String() method), protobuf (sinh từ .proto files), mockery (sinh mock). Chạy go generate ./... để thực thi tất cả directives.
1package main23import "fmt"45//go:generate stringer -type=Color67type Color int89const (10 Red Color = iota11 Green12 Bluego.work file lets you work with multiple modules at once. Useful for monorepos or when developing a library alongside an app. go work init creates the file. go work use -r ./... adds all modules.
go.work file cho phép làm việc với nhiều module cùng lúc. Hữu ích cho monorepo hoặc khi phát triển library cùng với ứng dụng. go work init tạo file. go work use -r ./... thêm tất cả module.
1// Create workspace2go work init ./mylib ./myapp34// go.work file5go 1.2167use (8 ./mylib9 ./myapp10)1112// Add modules13go work use -r ./...1415// Remove module16go work edit -dropuse ./oldmodule1718// View workspace19cat go.workKey Takeaways
Điểm Chính
- go fmt automatically formats code, making style debates unnecessarygo fmt tự động định dạng code, làm cho tranh cãi về style không cần thiết
- go test -race detects concurrent access to shared memorygo test -race phát hiện truy cập đồng thời vào bộ nhớ dùng chung
- Cross-compilation is simple with GOOS and GOARCH environment variablesCross-compilation rất đơn giản với các biến môi trường GOOS và GOARCH
- golangci-lint aggregates multiple linters for comprehensive code checkinggolangci-lint tập hợp nhiều linter để kiểm tra code toàn diện
Practice
Test your understanding of this chapter
What is the difference between go build and go install?
Sự khác biệt giữa go build và go install là gì?
How do you cross-compile a Go program for Linux from macOS?
Làm thế nào để cross-compile chương trình Go cho Linux từ macOS?
go vet is built into Go and can detect unused variables, unreachable code, and incorrect Printf format verbs.
go vet được xây dựng trong Go và có thể phát hiện biến không sử dụng, code không thể truy cập và format verb Printf không chính xác.
golangci-lint replaces the need for go fmt and go vet.
golangci-lint thay thế nhu cầu về go fmt và go vet.
Fill in the command to update a Go project's dependencies
Điền vào lệnh để cập nhật các dependency của dự án Go
go mod