为了账号安全,请及时绑定邮箱和手机立即绑定

创建路由模块 Go/Echo RestAPI

创建路由模块 Go/Echo RestAPI

Go
慕莱坞森 2023-07-17 13:58:26
我刚刚开始学习 Go,想创建自己的 REST API。问题很简单:我想将 api 的路由放在不同的文件中,例如:routes/users.go,然后将其包含在“main”函数中并注册这些路由。Echo/Go 中有大量的restAPI 示例,但它们都在 main() 函数中具有路由。我检查了一些示例/github 入门套件,但似乎找不到我喜欢的解决方案。func main() {    e := echo.New()    e.GET("/", func(c echo.Context) error {        responseJSON := &JSResp{Msg: "Hello World!"}        return c.JSON(http.StatusOK, responseJSON)    })     //I want to get rid of this    e.GET("users", UserController.CreateUser)    e.POST("users", UserController.UpdateUser)    e.DELETE("users", UserController.DeleteUser)    //would like something like    // UserRoutes.initRoutes(e)    e.Logger.Fatal(e.Start(":1323"))}//UserController.go//CreateUser func CreateUser(c echo.Context) error {    responseJSON := &JSResp{Msg: "Create User!"}    return c.JSON(http.StatusOK, responseJSON)}//UserRoutes.gofunc initRoutes(e) { //this is probably e* echo or something like that//UserController is a package in this case that exports the CreateUser function    e.GET("users", UserController.CreateUser)     return e;}有没有简单的方法可以做到这一点?来自node.js并且仍然存在一些语法错误当然可以解决它们,但我目前正在努力解决我的代码架构。
查看完整描述

1 回答

?
qq_笑_17

TA贡献1818条经验 获得超7个赞

我希望将 api 的路由放在不同的文件中,例如:routes/users.go,然后将其包含在“main”函数中并注册这些路由。


这是可能的,只需让包中的文件routes声明接受实例的函数*echo.Echo并让它们注册处理程序即可。


// routes/users.go


func InitUserRoutes(e *echo.Echo) {

    e.GET("users", UserController.CreateUser)

    e.POST("users", UserController.UpdateUser)

    e.DELETE("users", UserController.DeleteUser)

}



// routes/posts.go


func InitPostRoutes(e *echo.Echo) {

    e.GET("posts", PostController.CreatePost)

    e.POST("posts", PostController.UpdatePost)

    e.DELETE("posts", PostController.DeletePost)

}

然后在main.go


import (

     "github.com/whatever/echo"

     "package/path/to/routes"

)


func main() {

    e := echo.New()

    routes.InitUserRoutes(e)

    routes.InitPostRoutes(e)

    // ...

}

请注意,这些InitXxx函数需要以大写字母开头,而不是您的initRoutes示例中第一个字母为小写。这是因为首字母小写的标识符是unexported 的,这使得它们无法从自己的包外部访问。换句话说,为了能够引用导入的标识符,您必须通过使其以大写字母开头来导出它。


更多信息请参见: https: //golang.org/ref/spec#Exported_identifiers


查看完整回答
反对 回复 2023-07-17
  • 1 回答
  • 0 关注
  • 65 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信