昨天的前言裡,我們談了這個系列的動機和最終目標:用 Golang、Elasticsearch 和 Kubernetes 打造一個雲原生搜尋服務。今天正式進入第一個實作:建立 專案骨架。
在開始寫程式之前,我們需要先把環境準備好,已經安裝 Golang 的工程師們請跳過這步。
到 Go 官方下載頁 安裝最新版本(建議 Go 1.24 以上)。
macOS(Homebrew):
brew install go
Ubuntu/Debian:
sudo apt update
sudo apt install golang
Windows:
直接下載 .msi
安裝檔並執行。
安裝完成後,在終端機輸入:
go version
會看到類似輸出:
新版本的 Go 預設使用 module 模式(go mod
),不一定要設定 GOPATH,但建議還是設一個工作目錄。
例如 macOS/Linux:
mkdir -p $HOME/go
echo "export GOPATH=$HOME/go" >> ~/.bashrc
echo "export PATH=$PATH:$GOPATH/bin" >> ~/.bashrc
source ~/.bashrc
Windows 可以在環境變數裡新增 GOPATH
,並把 %GOPATH%\bin
加入 PATH。
建議裝好之後先試試自動補完、跳轉、Lint,確保開發體驗順暢。
首先建立專案目錄,並用 go mod init
初始化 module。這是 Golang 專案管理依賴的基礎。
mkdir cloud-native-search && cd cloud-native-search
go mod init github.com/<yourname>/cloud-native-search
這樣會生成 go.mod
檔案,未來安裝的第三方套件都會寫在這裡。
我們先從一個最小的 REST 端點 /healthz
開始,確認伺服器可以正常啟動與回應。
建立 main.go
:
package main
import (
"fmt"
"log"
"net/http"
)
func healthHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "ok")
}
func main() {
http.HandleFunc("/healthz", healthHandler)
port := ":8080"
log.Printf("Server listening on %s", port)
if err := http.ListenAndServe(port, nil); err != nil {
log.Fatal(err)
}
}
啟動伺服器:
go run main.go
然後用 curl
測試:
curl http://localhost:8080/healthz
# ok
這代表我們的 REST API 框架已經建立,後續的功能都能往這個骨架延伸。
到今天為止,我們已經完成:
/healthz
雖然這一步很簡單,但它像是蓋房子前打的第一根樁,未來我們會在這個基礎上加入 logging、錯誤處理、context、並發 worker、甚至串接 Elasticsearch。