01main.go: Build Identity และ Runtime Bootstrap
main.go คือ composition root ของ executable: รวม dependency, อ่าน configuration, เปิด observability และเริ่ม server ส่วน package-level variables และ init() จะทำงานก่อน main() แบบลำดับเดียว จึงควรหลีกเลี่ยงงานที่ซ่อน side effect, ติดต่อ network หรือทำให้โปรแกรมทดสอบยากใน init()
// go build -ldflags "-X main.commit=123456"
var commit string
//go:embed VERSION
var version string
func init() {
if os.Getenv("GOMAXPROCS") != "" {
runtime.GOMAXPROCS(0) // อ่านค่าเดิม ไม่ได้ตั้งค่า
} else {
runtime.GOMAXPROCS(1) // บังคับให้ Go code ขนานได้สูงสุด 1 P
}
if os.Getenv("GOMEMLIMIT") != "" {
debug.SetMemoryLimit(-1) // อ่านค่าเดิม ไม่ได้ตั้งค่า
}
}Build Metadata: ldflags และ go:embed
ค่าเริ่มต้นเป็น empty string และ linker เปลี่ยนค่าได้ด้วย -X main.commit=123456
เหมาะกับ log, health/version endpoint และ incident correlation ควรกำหนด fallback เช่น dev
นำเนื้อหาไฟล์ VERSION เข้า binary ตอน compile เป็น string
เปลี่ยนไฟล์หลัง build ไม่กระทบ binary ต้องมี import _ "embed" และควร trim newline
ทำงานหลัง package variables และก่อน main โดยอัตโนมัติ
error handling และ dependency มองไม่ชัด ควรใช้เฉพาะ invariant เล็ก ๆ หรือ registration ที่จำเป็น
Linker flag -X ใช้ได้กับตัวแปรชนิด string ที่ไม่ได้กำหนดค่า หรือกำหนดจาก constant string expression เท่านั้น ถ้า build โดยไม่ส่ง flag ค่า commit ในตัวอย่างเดิมจะเป็นสตริงว่าง ส่วน VERSION เป็น snapshot ตอน build ไม่ใช่ไฟล์ configuration ที่อ่านใหม่ตอน runtime
Runtime Configuration: โค้ดนี้ตั้งค่าอะไรจริง?
เมื่อ argument ต่ำกว่า 1 จะคืนค่าปัจจุบันโดย ไม่เปลี่ยนค่า
branch ที่พบ environment variable จึงเป็นเพียง query และค่าจาก environment ถูก runtime ใช้ไปแล้ว
จำกัด Go code ให้ execute พร้อมกันได้สูงสุดหนึ่ง logical P
ลด CPU parallelism/GC assist และปิด automatic GOMAXPROCS updates อาจลด throughput บน container ที่มีมากกว่า 1 CPU
argument ติดลบจะคืน soft memory limit ปัจจุบันโดย ไม่เปลี่ยนค่า
ถ้ามี GOMEMLIMIT runtime ได้อ่านตอนเริ่ม process แล้ว การเรียกนี้จึงไม่มีผลถ้าไม่เก็บค่าที่คืนมา
ถ้าเจตนาคือใช้ค่าจาก environment ให้ลบ init() นี้ได้เลยและปล่อย runtime จัดการ ถ้าเจตนาคือแสดงค่าที่มีผล ให้อ่านแล้ว log อย่างชัดเจนใน startup path ดังตัวอย่างต่อไปนี้
package main
import (
_ "embed"
"log/slog"
"runtime"
"runtime/debug"
"strings"
)
var commit = "dev"
//go:embed VERSION
var versionFile string
func main() {
slog.Info("starting",
"version", strings.TrimSpace(versionFile),
"commit", commit,
"gomaxprocs", runtime.GOMAXPROCS(0),
"gomemlimit", currentMemoryLimit(),
)
// start server...
}
func currentMemoryLimit() int64 {
return debug.SetMemoryLimit(-1)
}อ่านเอกสารทางการ: Go embed ↗
อ่านเอกสารทางการ: Go Specification: Package Initialization ↗
อ่านเอกสารทางการ: Go runtime.GOMAXPROCS ↗
อ่านเอกสารทางการ: Go runtime/debug.SetMemoryLimit ↗
02Goroutine, Channel และ Mutex
Goroutine คือฟังก์ชันที่ถูก schedule โดย Go runtime บน OS threads จำนวนหนึ่ง การสร้าง goroutine ราคาถูกกว่า thread แต่ไม่ฟรี ทุกตัวใช้ stack, scheduler time และอาจถือ reference จน memory ไม่ถูกเก็บคืน ดังนั้น “สร้าง goroutine ต่อ request ได้” ไม่ได้แปลว่า “สร้างได้ไม่จำกัด”
Channel เหมาะกับการส่ง ownership ของข้อมูลหรือประสาน workflow ระหว่าง goroutine ส่วน Mutex เหมาะกับการปกป้อง shared state ที่มีเจ้าของชัดเจน อย่าเลือก channel เพียงเพราะดูเป็น Go กว่า—ถ้าโจทย์คือ cache map ที่อ่านบ่อยและเขียนน้อย `RWMutex` อาจตรงกว่า
Unbuffered channel
ผู้ส่งและผู้รับต้อง rendezvous กัน เหมาะเมื่ออยากได้ synchronization ที่ชัดเจน
Buffered channel
แยกจังหวะ producer/consumer ได้ชั่วคราว แต่ buffer ไม่ใช่วิธีแก้ consumer ช้าถาวร
Bounded concurrency
ใช้ semaphore หรือ worker pool จำกัดงานพร้อมกัน ป้องกัน DB และ downstream ล่มตาม
03Context คือสัญญาณควบคุมอายุงาน
`context.Context` พา deadline, cancellation และ request-scoped metadata ข้ามขอบเขตฟังก์ชัน เมื่อ client ตัดการเชื่อมต่อหรือ request หมดเวลา งาน DB และ HTTP call ด้านล่างควรหยุดตาม ไม่ใช่ทำต่อจนสิ้นเปลือง resource
- รับ `ctx` เป็น argument แรก และอย่าเก็บไว้ใน struct ระยะยาว
- derive จาก parent context เพื่อรักษา cancellation chain
- เรียก `defer cancel()` ทุกครั้งที่ใช้ `WithTimeout` หรือ `WithCancel`
- ใช้ value เฉพาะ metadata ที่เดินทางกับ request เช่น correlation ID
func GetPolicy(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 800*time.Millisecond)
defer cancel()
policy, err := service.FindPolicy(ctx, r.PathValue("id"))
if err != nil {
switch {
case errors.Is(err, context.DeadlineExceeded):
writeError(w, 504, "upstream timeout")
case errors.Is(err, domain.ErrNotFound):
writeError(w, 404, "policy not found")
default:
logger.ErrorContext(ctx, "find policy", "err", err)
writeError(w, 500, "internal error")
}
return
}
writeJSON(w, 200, policy)
}04Error handling และ HTTP boundary
ใน Go error เป็น value จึงควรเพิ่มบริบทขณะส่งต่อด้วย `%w` แล้วตรวจด้วย `errors.Is` หรือ `errors.As` แทนการเทียบข้อความ ชั้น service ควรคืน domain error ส่วน HTTP handler เป็นคน map เป็น status code เพื่อไม่ให้ domain ผูกกับ transport
fmt.Errorf("load policy %s: %w", id, err) รักษา cause และเพิ่มบริบทสำหรับ debug
log error ทุกชั้นจนข้อความเดียวกันซ้ำหลายครั้ง หรือคืนรายละเอียด database ให้ client
05Unit Test ใน Go และ TDD
เริ่มจาก testing และ Table-driven Test
Go มี test runner อยู่ใน toolchain แล้ว: วาง test ในไฟล์ที่ลงท้ายด้วย_test.go ตั้งชื่อฟังก์ชัน TestXxx และรับ*testing.T จากนั้นรันด้วย go test ./...รูปแบบ table-driven test ช่วยรวมหลายกรณีไว้ในโครงเดียว และใช้t.Run ตั้งชื่อแต่ละกรณีให้ผลลัพธ์อ่านง่าย
func TestNormalizeEmail(t *testing.T) {
tests := []struct {
name string
input string
want string
wantErr bool
}{
{name: "trim and lowercase", input: " USER@EXAMPLE.COM ", want: "user@example.com"},
{name: "empty email", input: " ", wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := NormalizeEmail(tt.input)
if (err != nil) != tt.wantErr {
t.Fatalf("NormalizeEmail() error = %v, wantErr %v", err, tt.wantErr)
}
if got != tt.want {
t.Errorf("NormalizeEmail() = %q, want %q", got, tt.want)
}
})
}
}เริ่มด้วย standard library ก่อน แล้วเพิ่ม library เมื่อช่วยลดงานซ้ำหรือทำให้ failure message ชัดขึ้น คำสั่งที่ควรอยู่ใน CI อย่างน้อยคือ go test ./... และควรรันgo test -race ./... กับโค้ด concurrent รวมถึงติดตาม coverage เพื่อหา blind spot ไม่ใช่ใช้เปอร์เซ็นต์เป็นเป้าหมายแทนคุณภาพ test
เลือก Testing Tools ให้ตรงหน้าที่
Test runner มาตรฐาน รองรับ subtest, benchmark, fuzzing และ helper โดยไม่เพิ่ม dependency
เป็นค่าเริ่มต้นสำหรับทุกโปรเจกต์ โค้ดตรงไปตรงมา แต่อาจต้องเขียน assertion และ diff เอง
มี assert, require, suiteและ mock สำหรับ test ที่ใช้ testing.T
เหมาะเมื่อ assertion ซ้ำมากและต้องการข้อความ failure ที่อ่านง่าย โดย require จะหยุด test case ทันทีเมื่อพัง
Framework แบบ behavior/spec ใช้ Describe,Context, It และ lifecycle hooks
เหมาะกับ integration หรือ acceptance suite ที่มี scenario ซับซ้อน แต่ทีมต้องเรียนรู้ DSL และควบคุม nesting ไม่ให้ลึกเกินไป
Matcher/assertion library ที่ใช้คู่กับ Ginkgo บ่อย และมีEventually/Consistently สำหรับ async behavior
ใช้กับ testing ปกติได้เช่นกัน เหมาะเมื่อ matcher สื่อเจตนาได้ดีกว่าการเขียนเงื่อนไขเอง
สร้าง strongly typed mock จาก interface และตรวจ expectation เรื่อง argument, จำนวนครั้ง และลำดับการเรียก
เหมาะกับ interaction ที่ boundary; ใช้แพ็กเกจที่ดูแลต่อโดย Uber คือ go.uber.org/mock แทน repo เดิมgolang/mock
Code generator สำหรับ interface mock รองรับ template แบบ Testify และ config กลางของโปรเจกต์
เหมาะกับทีมที่ใช้ Testify/mock หรือมี interface จำนวนมาก; เป็นตัวสร้าง mock ไม่ใช่ test runner
Mock เฉพาะ Boundary ที่จำเป็น
สร้าง interface ฝั่ง code ที่เรียก dependency เช่น repository, payment gateway, clock หรือ ID generator แล้ว inject เข้ามาใน service ถ้าต้องจำลอง state และ behavior หลายขั้น fake ขนาดเล็กมักอ่านง่ายกว่า mock ที่มี expectation จำนวนมาก ส่วน pure function และ value object ควรทดสอบตรง ๆ โดยไม่ใช้ mock
TDD คืออะไร และทำอย่างไร
Test-Driven Development (TDD) คือการใช้ test ขับการออกแบบทีละ behavior สั้น ๆ ไม่ใช่เพียงเขียน test ให้ครบหลังเขียนโค้ดเสร็จ วงจรหลักคือ Red → Green → Refactor
- 1เลือก behavior ที่เล็กที่สุด
เขียนตัวอย่าง input/output หรือ business rule หนึ่งข้อ และกำหนด API ที่ผู้เรียกอยากใช้
- 2Red — เขียน test ที่ยังไม่ผ่าน
รัน test เพื่อยืนยันว่ามัน fail ด้วยเหตุผลที่คาดไว้ ไม่ใช่เพราะ syntax หรือ setup ผิด
- 3Green — เขียนโค้ดให้น้อยที่สุดจนผ่าน
ยังไม่เพิ่ม abstraction หรือรองรับกรณีที่ไม่มี test ให้ feedback loop สั้นและชัดเจน
- 4Refactor — ปรับโครงสร้างโดย behavior เดิมยังผ่าน
ลด duplication ปรับชื่อและ boundary แล้วรัน test ซ้ำ ก่อนเริ่ม behavior ถัดไป
ในงานจริงเริ่มจาก happy path ที่เล็กที่สุด แล้วเพิ่ม invalid input, boundary case และ failure ของ dependency ทีละกรณี TDD เหมาะมากกับ business rule ที่ตัวอย่างชัดเจน แต่อาจไม่คุ้มกับ prototype, exploratory code หรือ UI detail ที่เปลี่ยนเร็ว—ยังต้องมี test ในระดับที่เหมาะสมก่อนส่ง production
อ่านเอกสารทางการ: Go testing package ↗อ่านเอกสารทางการ: Testify ↗
อ่านเอกสารทางการ: Ginkgo v2 ↗
อ่านเอกสารทางการ: Gomega ↗
อ่านเอกสารทางการ: GoMock maintained by Uber ↗
อ่านเอกสารทางการ: Mockery v3 ↗
06API ที่รับ traffic สูง
เริ่มจากกำหนด timeout budget ทั้ง request แล้วแบ่งให้แต่ละ downstream จากนั้นใช้ connection pool ที่สัมพันธ์กับความสามารถของ DB, จำกัด concurrency, ทำ pagination และรองรับ graceful shutdown เพื่อหยุดรับงานใหม่แต่ให้งานเดิมจบภายใน deadline
สำหรับคำสั่งที่ retry ได้ เช่น “ส่งคำขอซื้อกรมธรรม์” ให้รับ idempotency key แล้วบันทึก key กับผลลัพธ์ใน transaction เดียวกัน หาก request เดิมมาอีกให้คืนผลเดิม ไม่สร้างรายการซ้ำ
อ่านเอกสารทางการ: Go context และ cancellation ↗