iT邦幫忙

2025 iThome 鐵人賽

DAY 15
0

在過去兩週,我們從 go mod init 開始,搭起專案骨架、加上測試框架、中介層、API、pprof、metrics,甚至打通本機 Elasticsearch。今天,我們要做的是:

✅ 清理專案目錄,避免日後難以維護

✅ 補上缺的測試,讓 coverage 基本過關

✅ 撰寫 README,方便未來自己與他人快速上手


Step 1:整理目錄結構

目前專案可能長這樣:

.
├── cmd/
│   └── server/        # main.go
├── internal/
│   ├── handler/       # HTTP handler
│   ├── search/        # SearchService 介面 + fake + es
│   ├── middleware/    # logging, recovery
│   └── metrics/       # Prometheus metrics
├── pkg/               # 可共用的 util
├── go.mod
├── go.sum
└── docker-compose.yml

這樣分層的好處:

  • cmd/:只放啟動程式
  • internal/:核心邏輯(不可被外部 import)
  • pkg/:通用工具(例如重試策略)
  • infra 檔案(docker-compose、Makefile、k8s yaml)都放在 repo root

Step 2:補測試

目標不是 100% coverage,而是把核心流程測起來:

  1. Handler 測試
    • /healthz 回傳 200
    • /search 在 FakeSearchService 下能回傳固定資料
func TestHealthz(t *testing.T) {
    req := httptest.NewRequest("GET", "/healthz", nil)
    w := httptest.NewRecorder()

    HealthzHandler(w, req)

    if w.Result().StatusCode != http.StatusOK {
        t.Errorf("expected 200, got %d", w.Result().StatusCode)
    }
}

  1. Service 測試
    • FakeSearchService:query → 預期結果
    • ESSearchService:只保留 smoke test,不強求 coverage
  2. Middleware 測試
    • Recovery:製造一個 panic,確保回傳 500 而不是掛掉

Step 3:撰寫 README

最後,把這兩週的工作整理成 README:

Cloud-Native Search Service (Phase 1: Golang)

Features

  • RESTful API with /healthz and /search
  • Context timeout on all external calls
  • Structured logging & recovery middleware
  • Retry with backoff + jitter
  • Worker pool for bounded concurrency
  • Benchmarking & profiling (pprof)
  • Metrics (QPS, latency) via Prometheus
  • SearchService interface (Fake & Elasticsearch)

Getting Started

git clone https://github.com/USERNAME/cloud-native-search.git
cd cloud-native-search
docker compose up -d es01
go run ./cmd/server

Open http://localhost:8080/search?q=golang

Tests

go test ./...

Next Step

Phase 2: Elasticsearch — 安裝、mapping、bulk 匯入、調優。


Step 4:小結

今天我們做了「穩定化」:

  1. 整理目錄結構 → 清楚分層
  2. 補上測試 → coverage 達到基本標準
  3. 撰寫 README → 未來快速上手

到這裡,Golang Phase(Day 2–15)完成
接下來,我們將進入 Elasticsearch Phase,正式深入 ES 的 mapping、查詢與效能調優。


上一篇
Day 14 - 打通真路徑:連上本機 ES 的 smoke test
下一篇
Day 16 - Recap:複習 Golang 內容
系列文
用 Golang + Elasticsearch + Kubernetes 打造雲原生搜尋服務20
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言