登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-03-03 16:57:25 463浏览 收藏

积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《在labstack/echo的路由中避免全局变量》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我正在使用 labstack/echo 网络服务器和 gofight 进行单元测试。在学习 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)

看起来你可以扩展上下文接口,但是它是在哪里创建的?这看起来像是使用了一种沮丧

e.GET("/", func(c echo.Context) error {
    cc := c.(*CustomContext)
}

我认为(可能是错误的)这仅在接口上允许,并且 echo.context.echo() 返回类型而不是接口。


解决方案


您可以将实例的方法作为函数值传递,这可能是处理此问题的最直接的方法:

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    
}

以上就是《在labstack/echo的路由中避免全局变量》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>