避免在 labstack/echo 的路由中使用全局变量

在学习 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 tests

func 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() 返回类型而不是接口。


子衿沉夜
浏览 207回答 1
1回答

芜湖不芜

您可以将实例的方法作为函数值传递,这可能是处理此问题的最直接的方法: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    }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go