移轉至 0.7.5 API
升級至 Spine v0.7.5 時,請確認 HTTP 輸入、上下文與應用程式組裝方式的變更。
升級至正式版
以下指令用於更新既有的 Echo 應用程式。若使用其他 HTTP 實作,請在平台指南中確認相容版本。使用 HTTP v2 的應用程式也須升級至對應的 HTTP v3 平台。
go install github.com/NARUBROWN/spine-cli/cmd/spine@v0.4.4
spine version
go get github.com/NARUBROWN/spine@v0.7.5 github.com/NARUBROWN/spine-echo-platform@v0.2.1控制器與 DTO
type UserPath struct {
ID int64 `path:"id"`
}
type UserQuery struct {
Name string `query:"name"`
}
type UserHeaders struct {
RequestID string `header:"X-Request-ID"`
}
type CreateUser struct {
Name string `json:"name" validate:"required"`
}
func (*UserController) RegisterRoutes(r *api.Registry) {
users := r.Group("/users", api.Interceptors((*Auth)(nil)))
users.GET("/:id", func(path input.Path[UserPath]) httpx.Response[map[string]int64] {
return httpx.Response[map[string]int64]{Body: map[string]int64{"id": path.ID}}
})
users.POST("/", func(body input.Body[CreateUser]) httpx.Response[CreateUser] {
return httpx.Response[CreateUser]{Body: *body, Options: httpx.ResponseOptions{Status: 201}}
})
}統一使用 input.Path[UserPath]、input.Query[UserQuery]、input.Header[UserHeaders]。HTTP 一般 *DTO 會被拒絕。Path/Query/Header 預設 lowerCamel,可用標籤覆寫。Body 遵循 json/xml/form 解碼規則。僅允許一個成功回應,多回應以及無效或衝突 XML 標籤在準備階段被拒絕。
組裝與自動驗證
engine, err := playground.New()
if err != nil {
return nil, boot.Options{}, err
}
app := spine.New(echoplatform.Option(), spine.WithValidator(engine))
app.Constructor(
constructor.Repository(&UserRepository{}),
constructor.Service(&UserService{}),
constructor.Controller(&UserController{}),
constructor.Interceptor(&Auth{}),
)將此片段放入具備所需型別與匯入的 BuildApplication。engine 是 playground.New 實例。自動標籤驗證不需要 DTO Validate 方法。額外方法須自行實作並在需要時呼叫 (*body).Validate(),OpenAPI 不推斷其方法本文。app.Validate 檢查應用設定。建構函式僅支援單回傳值,拒絕可變參數。
上下文與攔截器
HTTP 處理器需要請求上下文時可以宣告 pkg/spine.Ctx。所有攔截器掛鉤都接收 pkg/spine.Ctx。仍相容直接注入標準 context.Context。資料庫和事件使用 ExecutionContext().Context(),執行值使用 Set/Get,HTTP/WS 使用公開檢視。全域和路由 PreHandle 均在綁定前執行。BeforeResponse 錯誤優先決定回應,HTTPError 只允許 400–599。AfterCompletion 在嘗試寫入後執行,不是提交點。
CLI 與相容程式碼
CLI v0.4.4 會產生 RegisterRoutes、角色建構器與 HTTP 輸入包裝型別。移轉後執行 go mod tidy、spine contract check 和 spine verify,再驗證實際的 HTTP 請求。 app.Route、route.WithInterceptors、query.Values、header.Values、path、multipart.UploadedFiles 均為已棄用相容 API,不用於新範例或產生程式碼。舊移轉文件描述歷史行為,目前 API 以本頁為準。
從 0.7.1 移轉
如果應用程式使用已撤回的 Go 模組版本 v0.7.1,請升級至 v0.7.5。為既有 HTTP 處理器中的 DTO 指標加上與輸入來源相符的包裝型別,並將 HTTP 平台更新至相容版本。
