下面是我使用 Labstack 的 Echo 用 Go 编写的 Web 应用程序的入口点:
package main
import (
"github.com/labstack/echo"
mw "github.com/labstack/echo/middleware"
)
func main() {
controller := controllers.NewUserController(getSession())
app := echo.New()
app.Use(mw.Logger())
app.Use(mw.Recover())
app.SetDebug(true)
app.Post("/users", controller.CreateUser)
app.Get("/users", controller.ListUsers)
app.Get("/users/:id", controller.GetUser)
app.Patch("/users/:id", controller.UpdateUser)
app.Delete("/users/:id", controller.DeleteUser)
app.Run(":8000")
}
如何重用Echo
应用程序中实例化的日志中间件?我试过这个:
包控制器
import (
"net/http"
"github.com/labstack/echo"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type (
UserController struct {
session *mgo.Session
}
)
func NewUserController(s *mgo.Session) *UserController {
return &UserController{s}
}
func (userController UserController) CreateUser(context *echo.Context) error {
user := &models.User{}
if err := context.Bind(user); err != nil {
context.Echo().Logger().Error("Error creating user")
return err
}
user.Id = bson.NewObjectId()
userController.session.DB("test").C("users").Insert(user)
context.Echo().Logger().Debug("Created user", id)
return context.JSON(http.StatusCreated, user)
}
即使上面的代码编译,语句
context.Echo().Logger().Debug("Created user", id)
不会产生任何输出......而以下语句会:
context.Echo().Logger().Info("Created user", id)
我错过了什么吗?