在學習 go 時,想知道是否有一個 go 習慣用法用于訪問(嵌入的)echo 結構之外的狀態。例如:type WebPlusDB struct {? ? web *echo.Echo? ? db? *databaseInterface}func NewEngine() *echo.Echo {? ? e := echo.New()? ? e.GET("/hello", route_hello)? ? return e? ??}func NewWebPlusDb() {? ? e := NewEngine()? ? db := database.New()? ?? ? return WebPlusDB{e,db}}// for use in unit testsfunc NewFakeEngine() *WebPlusDB {? ? e := NewEngine()? ? db := fakeDatabase.New()? ?? ? return WebPlusDB{e,db}}? ??func route_hello(c echo.Context) error {? ? log.Printf("Hello world\n")? ? // how do I access WebPlusDB.db from here?? ? return c.String(http.StatusOK, "hello world")}然后在測試代碼中我使用:import (? ? "github.com/labstack/echo"? ? "github.com/appleboy/gofight"? ? "github.com/stretchr/testify/assert"? ? "testing")func TestHelloWorld(t *testing.T) {? ? r := gofight.New()? ? r.GET("/hello").? ? ? ? ? Run(NewFakeEngine(), func(r gofight.HTTPResponse, rq gofight.HTTPRequest) {? ? ? ? assert.Equal(t, http.StatusOK, r.Code)? ? ? ? assert.Equal(t, "hello world", r.Body.String())? ? ? ? // test database access? ? })}最簡單的解決方案是必須使用全局變量,而不是在“WebPlusDB”中嵌入 echo 并在其中添加狀態。我想要更好的封裝。我認為我應該使用類似 WebPlusDB 結構的東西,而不是 echo.Echo 加上全局狀態。這對于單元測試來說也許并不重要,但在 go 中正確做事的更大計劃中(在這種情況下避免全局變量)我想知道。有沒有解決方案或者這是 echo 設計中的弱點?它具有中間件的擴展點,但數據庫后端并不是此處定義的真正的中間件。注意:我在這里使用數據庫來說明常見情況,但它可以是任何東西(我實際上使用的是amqp)看起來你可以擴展上下文接口,但是它是在哪里創建的呢?這看起來像是使用了一種downcast:e.GET("/", func(c echo.Context) error {? ? cc := c.(*CustomContext)}我認為(可能是錯誤的)這僅在接口上允許,并且 echo.Context.Echo() 返回類型而不是接口。
1 回答

蕪湖不蕪
TA貢獻1796條經驗 獲得超7個贊
您可以將實例的方法作為函數值傳遞,這可能是處理此問題的最直接的方法:
type WebPlusDB struct {
web *echo.Echo
db *databaseInterface
}
func (w WebPlusDB) route_hello(c echo.Context) error {
log.Printf("Hello world\n")
// do whatever with w
return c.String(http.StatusOK, "hello world")
}
func NewEngine() *echo.Echo {
e := echo.New()
w := NewWebPlusDb()
e.GET("/hello", w.route_hello)
return e
}
- 1 回答
- 0 關注
- 177 瀏覽
添加回答
舉報
0/150
提交
取消