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.