slog, health check, graceful shutdown, Docker
env > flag > file อย่า hardcode รหัส:
port := os.Getenv("PORT")
if port == "" { port = "8080" }
dsn := os.Getenv("DATABASE_URL") // รหัสห้าม commit ลง gitimport "log/slog"
slog.Info("start", "port", port)
slog.Error("db fail", "err", err) // อย่า log token เต็ม มาสก์ก่อนอยากได้ JSON ส่งไป log server ใช้ slog.New(slog.NewJSONHandler(os.Stdout, nil))
/healthz = ตอบ 200 ถ้ายังหายใจ (ให้ K8s/ALB เช็ก) + /readyz เช็ก DB ด้วย PingContextcontext.WithValue (เก็บแค่ id เล็กๆ ไม่ยัดของใหญ่)mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("ok")) })srv := &http.Server{Addr: ":"+port, Handler: mux}
go srv.ListenAndServe()
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
srv.Shutdown(ctx) // รอแขกเก่ากลับก่อนค่อยปิดทุก call นอก (DB/HTTP) ต้องมี timeout ผ่าน context ไม่งั้น shutdown ค้าง
FROM golang:1.27 AS build
WORKDIR /app
COPY . .
RUN CGO_ENABLED=0 go build -o app .
FROM gcr.io/distroless/base
COPY --from=build /app/app /app
CMD ["/app"]CGO_ENABLED=0 = ไฟล์เดียวจบ (1.26 cgo เร็วขึ้น 30% แต่ถ้าไม่ใช้ C ปิดไปเลยเล็กสุด)
CI ขั้นต่ำ:
ดูอาการ production: GODEBUG=gctrace=1 ดู GC + pprof -http เปิด flame graph (1.26 default) หาแท่งกว้างสุดก่อนแก้
อ้างอิง: std slog net/http signal, Go 1.26 (cgo/GC/pprof), Go 1.27 release
log := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelInfo,
}))
log.Info("server เริ่ม", "port", 8080)mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
if err := db.PingContext(r.Context()); err != nil {
http.Error(w, "db down", http.StatusServiceUnavailable)
return
}
w.Write([]byte("ok"))
})ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
srv := &http.Server{Addr: ":8080", Handler: mux}
go srv.ListenAndServe()
<-ctx.Done() // รอ Ctrl+C
srv.Shutdown(context.Background()) // รอ request ค้างเสร็จก่อนเลิก/healthz เช็ก dependency จริง (ping DB)