Chuyển đến nội dung chính

Lesson 1: Introducing Go - Cloud Native language

Why Go? Compare with Rust, Java, Python. History, design philosophy, Go ecosystem. Install, GOPATH, Go modules. Hello World and go toolchain.

💻 Programming — Lesson 1 Lesson 1: Introducing Go - The language of Cloud Native

Golang: From Basics to Advanced

Part 1: Go Fundamentals

xdev.asia

1. What is Go?

Go (or Golang) is an open source programming language created by Robert Griesemer, Rob Pike and Ken Thompson at Google in 2007, officially released in 2009. Go was designed to solve real problems in large-scale software development: compile quickly, simple concurrency, deployment is easy.

Go is a language statically typed, compiled, creating a unique binary with no runtime dependencies. This is why Go is the top choice for Cloud Native — Docker, Kubernetes, Terraform, Prometheus, etcd are all written in Go.

Outstanding features

  • Simple & readable: Only 25 keywords, minimalist syntax, easy to read code
  • Fast compilation: Compile entire large projects in seconds
  • Built-in concurrency: Goroutines and Channels are first-class citizens
  • Static binary: Single binary, easy cross-compile for any OS/architecture
  • Garbage collected: Efficient GC, low latency (sub-millisecond from Go 1.19+)
  • Rich standard library: HTTP server, JSON, crypto, testing... built-in

2. Why choose Go?

Go in Industry

Go is widely used by large companies:

CompanyProducts using Go
GoogleKubernetes, gVisor, many internal services
DockerDocker Engine, Docker Compose
HashiCorpTerraform, Consul, Vault, Nomad
UberMicroservices platform, Jaeger tracing
CloudflareEdge computing, DNS, security tools
TwitchChat service (process millions messages/sec)
NetflixInfrastructure tooling
DropboxMigration from Python to Go for performance

Most suitable use cases

  • Microservices & APIs: REST, gRPC, GraphQL backends
  • Cloud infrastructure: CLI tools, operators, controllers
  • DevOps tooling: CI/CD, monitoring, automation
  • Networking: Proxies, load balancers, VPN
  • Data pipelines: ETL, stream processing
  • Blockchain: Ethereum Go client (Geth)

3. Compare Go with other languages

CriteriaGoRustJavaPythonNode.js
TypingStaticStaticStaticDynamicDynamic
CompilationNative binaryNative binaryJVM bytecodeInterpretedJIT (V8)
GCYes (low latency)No (ownership)Yes (JVM GC)YesYes (V8 GC)
ConcurrencyGoroutinesasync/await + threadsVirtual ThreadsasyncioEvent loop
Learning CurveLowHighAverageLowLow
PerformanceHighVery highHighLowAverage
Memory UsageLowVery lowHighHighAverage
Deploy Size~10-20MB~5-15MBJRE + JARRuntime + depsRuntime + node_modules
EcosystemGoodDevelopingVery bigVery bigVery big

When to choose Go instead of Rust? Go when you need to write quickly, team onboarding quickly, GC acceptable. Rust when you need zero-cost abstractions, absolute memory safety, embedded/systems.

When to choose Go instead of Java? Go when you need container-friendly (compact, fast start), no need for JVM ecosystem. Java when needed Spring ecosystem, enterprise standards, legacy integration.

4. Go's design philosophy

Go follows very special design principles:

4.1. Simplicity over cleverness

// Go: explicit, simple
if err != nil {
    return fmt.Errorf("failed to read file: %w", err)
}

// Không có: exceptions, try-catch, generics phức tạp
// Không có: inheritance, ternary operator
// Không có: optional chaining, null coalescing

4.2. Composition over Inheritance

// Go sử dụng embedding thay vì inheritance
type Animal struct {
    Name string
}

func (a Animal) Speak() string {
    return a.Name + " speaks"
}

type Dog struct {
    Animal  // embedding, không phải inheritance
    Breed string
}

// Dog "kế thừa" method Speak() từ Animal
dog := Dog{Animal: Animal{Name: "Rex"}, Breed: "Labrador"}
fmt.Println(dog.Speak()) // "Rex speaks"

4.3. Concurrency is not parallelism

Rob Pike: "Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once."

// Goroutines: lightweight concurrent execution
go func() {
    // Chạy concurrent, chi phí ~2KB stack
}()

// Channels: communication between goroutines
ch := make(chan string)
go func() { ch <- "hello" }()
msg := <-ch

4.4. One way to format

gofmt Automatically format code according to unique standards. No more arguing about code style.

5. Install Go

5.1. macOS

# Cách 1: Homebrew (khuyến nghị)
brew install go

# Cách 2: Download từ go.dev
# Tải file .pkg từ https://go.dev/dl/ và cài đặt

# Verify
go version
# go version go1.23.x darwin/arm64

5.2. Linux (Ubuntu/Debian)

# Download và extract
wget https://go.dev/dl/go1.23.4.linux-amd64.tar.gz
sudo rm -rf /usr/local/go
sudo tar -C /usr/local -xzf go1.23.4.linux-amd64.tar.gz

# Thêm vào PATH (thêm vào ~/.bashrc hoặc ~/.zshrc)
export PATH=$PATH:/usr/local/go/bin
export GOPATH=$HOME/go
export PATH=$PATH:$GOPATH/bin

# Verify
go version

5.3. Windows

# Cách 1: Winget
winget install GoLang.Go

# Cách 2: Download .msi từ https://go.dev/dl/

# Verify (mở terminal mới)
go version

5.4. GOPATH and Go Workspace

# Xem cấu hình Go
go env

# Các biến quan trọng:
# GOROOT  = /usr/local/go       (Go installation)
# GOPATH  = $HOME/go            (Go workspace)
# GOBIN   = $GOPATH/bin         (Compiled binaries)
# GOMODCACHE = $GOPATH/pkg/mod  (Module cache)

# Go workspace structure:
# ~/go/
# ├── bin/        ← Installed binaries (golangci-lint, air, etc.)
# ├── pkg/mod/    ← Downloaded module cache
# └── src/        ← (Legacy, không dùng với modules)

6. Hello World - The first Go program

6.1. Initialize project

# Tạo thư mục project
mkdir hello-go && cd hello-go

# Khởi tạo Go module
go mod init github.com/yourname/hello-go
# Tạo file go.mod - quản lý dependencies

6.2. Write code

// main.go
package main

import "fmt"

func main() {
    fmt.Println("Hello, Go! 🚀")
    
    // Variables
    name := "Gopher"  // short declaration
    age := 15         // Go ra đời 2009
    
    fmt.Printf("Xin chào %s, Go đã %d tuổi!\n", name, age)
}

6.3. Run and Build

# Chạy trực tiếp (compile + run)
go run main.go
# Output: Hello, Go! 🚀
# Output: Xin chào Gopher, Go đã 15 tuổi!

# Build binary
go build -o hello-go main.go
./hello-go

# Cross-compile cho Linux (từ macOS)
GOOS=linux GOARCH=amd64 go build -o hello-go-linux main.go

# Cross-compile cho Windows 
GOOS=windows GOARCH=amd64 go build -o hello-go.exe main.go

7. Go Toolchain

Go comes with a powerful set of tools, no additional installation required:

CommandPurpose
go runCompile and run directly
go buildCompile into binary
go testRun tests
go fmtFormat code according to standards
go vetDetect potential errors
go mod initInitialize new module
go mod tidyClean up dependencies
go getDownload dependencies
go installCompile and install binary into $GOBIN
go readSee documentation
go generateRun code generation
go workWorkspace mode (multi-module)
# Xem docs của một package
go doc fmt
go doc fmt.Printf

# Format toàn bộ project
go fmt ./...

# Kiểm tra lỗi tiềm ẩn
go vet ./...

# Download và clean dependencies
go mod tidy

8. Editor Setup

8.1. VS Code (recommended)

// Cài extension: "Go" by Go Team at Google

// settings.json
{
  "go.formatTool": "goimports",
  "go.lintTool": "golangci-lint",
  "go.useLanguageServer": true,
  "editor.formatOnSave": true,
  "[go]": {
    "editor.defaultFormatter": "golang.go",
    "editor.codeActionsOnSave": {
      "source.organizeImports": "explicit"
    }
  }
}

8.2. GoLand (JetBrains)

GoLand is a specialized IDE for Go, with the best support for debugging, refactoring, and testing. Suitable for large projects.

8.3. Essential Tools

# golangci-lint - meta-linter (chạy 50+ linters)
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest

# air - live reload khi phát triển
go install github.com/air-verse/air@latest

# gotests - generate test stubs
go install github.com/cweill/gotests/gotests@latest

# mockery - generate mocks  
go install github.com/vektra/mockery/v2@latest

# swag - Swagger docs generation
go install github.com/swaggo/swag/cmd/swag@latest

9. Basic Go Modules

Go Modules (since Go 1.11) is the official dependency management system:

# go.mod - khai báo module và dependencies
module github.com/yourname/hello-go

go 1.23

require (
    github.com/gin-gonic/gin v1.10.0
    github.com/joho/godotenv v1.5.1
)
# Thêm dependency
go get github.com/gin-gonic/gin@latest

# Update dependency
go get -u github.com/gin-gonic/gin

# Remove unused dependencies  
go mod tidy

# Vendor dependencies (copy vào project)
go mod vendor

10. Standard Project Structure

Theo golang-standards/project-layout:

my-go-project/
├── cmd/                    # Entry points (main packages)
│   ├── api/
│   │   └── main.go         # API server
│   └── worker/
│       └── main.go         # Background worker
├── internal/               # Private packages (không thể import từ ngoài)
│   ├── handler/            # HTTP handlers
│   ├── service/            # Business logic
│   ├── repository/         # Data access
│   └── model/              # Domain models
├── pkg/                    # Public packages (có thể import)
│   └── validator/
├── config/                 # Configuration files
├── migrations/             # Database migrations
├── api/                    # API specs (OpenAPI, protobuf)
├── scripts/                # Build, deploy scripts
├── go.mod
├── go.sum
├── Makefile
├── Dockerfile
└── README.md

11. Summary

Go is a simple yet powerful language, designed for the cloud-native era. With fast compilation, concurrency built-in, static binary, and rich standard library, Go is ideal for backend services, microservices, and infrastructure tooling.

In the next article, we will go deeper Variables, Types & Control Flow — the syntactic foundation of Go.