# 元件用法

Source: https://gortexa.sheng.page/components/

框架的每個 package 都可以在 `go get` 之後單獨引用。先取得模組：

```bash
go get github.com/yshengliao/gortexa@v0.28.3
```

本節按類別列出公開元件，每個都附用途、import 路徑與一段最小用法；這些片段全部對 v0.28.3 編譯驗證過。

- [核心](https://gortexa.sheng.page/components/core/)：`kernel`、`config`、`interceptor`、`auth`、`apperr` —— 組裝、設定、攔截器鏈、JWT 與錯誤模型。
- [HTTP 與 MCP](https://gortexa.sheng.page/components/http-mcp/)：`httpcompat`、`mcp` —— grpc-gateway HTTP/JSON 層與 MCP bridge。
- [內建元件](https://gortexa.sheng.page/components/batteries/)：`mq`、`cache`、`storage`、`client` —— 訊息、快取、資料庫池與對外 client。
- [可觀測性與健康](https://gortexa.sheng.page/components/observability/)：`health`、`observability` —— 三態健康與 OTLP 日誌／追蹤／指標。

只要一個最小 app（不掛 gateway／MCP）見[以模組使用](https://gortexa.sheng.page/quickstart/#以模組使用不走-scaffold)。

注意：本節是給「不走 scaffold、直接把框架當 library」的用法。`gortexa create` 產出的專案已內含一份框架原始碼；自 v0.28.0 起那種專案也能再 `go get` 框架而不會撞 descriptor，但等於連進兩份框架程式碼，取捨見[手動快速開始](https://gortexa.sheng.page/quickstart/#以模組使用不走-scaffold)末段的說明。

## 完整接線

框架 repo 的 `cmd/server/main.go` 是所有元件組成一個服務的正規範例，順序為：

1. `config.MustBuild(...)` — fail-loud 載入設定。
2. `observability.SetupLogs／SetupTracing／SetupMetrics` — 各得一個 `ShutdownFunc`；`observability.NewGovernanceMetrics()`。
3. `auth.NewVerifier(...)`。
4. `interceptor.NewSet(interceptor.Config{...})`。
5. `kernel.New(WithConfig, WithLogger, WithInterceptors, WithStatsHandler(observability.ServerStatsHandler()), WithHTTPWrap(...), WithShutdownHook×3)`。
6. 把 service 註冊到 `app.GRPCServer()`；`app.Health().Register(...)`。
7. `conn, err := app.Loopback()` → `httpcompat.NewServeMux` → `app.SetGateway(...)`。
8. `mcp.ServiceDescriptors(...)` → `mcp.NewBridge(conn, descs, apperr.Default, cfg.Observ)` → `app.SetMCPHandler(bridge.Handler())`。
9. `app.Run(ctx)`。

`app.Loopback()` 必須在 `kernel.New` 之後、`Run` 之前呼叫；gateway 與 MCP bridge 都經它 dial，因而共用同一條攔截器鏈。

## testutil — 測試輔助（test-only）

in-process 測試輔助：bufconn gRPC server（掛完整攔截器鏈）、golden 檔比對、goroutine leak 斷言。

```go
import "github.com/yshengliao/gortexa/testutil"

conn := testutil.NewTestServer(t, func(s *grpc.Server) {
	pb.RegisterThingServiceServer(s, myService)
}, testutil.WithAuthSecret(secret))
// testutil.Golden(t, name, got) 比對 testdata/<name>.golden
// 設 GORTEXA_UPDATE_GOLDEN 才改寫 golden 檔（無 -update flag）
```
