douxun4173 2019-06-13 15:10 采纳率: 0%
浏览 91
已采纳

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

I am using the labstack/echo webserver and gofight for unit testing. In learning go would like to know if there is a go idiom for accessing state outside of the (embedded) echo structure. For example:

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
")

    // how do I access WebPlusDB.db from here?

    return c.String(http.StatusOK, "hello world")
}

Then in the test code I use:

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
    })

}

The easiest solution is to have to use a global variable instead of embedding echo in "WebPlusDB" and adding the state there. I would like better encapsulation. I think I should be using something like the WebPlusDB structure not an echo.Echo plus global state. This perhaps doesn't matter so much for unit testing but in the greater scheme of doing things right in go (in this case avoiding globals) I would like to know.

Is there a solution or is this a weakness in the design of echo? It has extension points for middleware but a database backend is not really middleware as defined here.

Note: I am using a database here to illustrate the common case but It could be anything (I am actually using amqp)

It looks like you can extend the context interface but where is it created? This looks like it uses a kind of downcast:

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

I think (perhaps incorrectly) that this is only allowed on interface and echo.Context.Echo() returns a type not an interface.

  • 写回答

1条回答 默认 最新

  • dongtan8979 2019-06-13 15:35
    关注

    You can pass a method of an instance as a function value, which is probably the most straightforward way to handle this:

    type WebPlusDB struct {
        web *echo.Echo
        db  *databaseInterface
    }
    
    func (w WebPlusDB) route_hello(c echo.Context) error {
        log.Printf("Hello world
    ")
    
        // 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    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?