go - 创建路由模块 Go/Echo RestAPI
问题描述
我刚开始学习 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.go
func 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 并且仍然有一些语法错误当然会解决它们,但我目前正在努力解决我的代码架构。
解决方案
我想将我的 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,这使得它们无法从它们自己的包外部访问。换句话说,为了能够引用导入的标识符,您必须通过使其以大写字母开头来导出它。
推荐阅读
- ibm-cloud - 使用 Lite 帐户创建免费的 IBM Cloud Analytics Engine 实例时出现错误“您的帐户未被授权选择 Lite 计划”
- java - 在 ListView 中动态添加 LinearLayout
- amazon-web-services - AWS DataSync 无法检测到源 NFS 文件系统中的任何文件
- sql - Json 中 Json 对象的 SQL 查询
- docker - /dev/stderr 上的权限被拒绝,这阻止我将日志重定向到 cloudwatch
- vscode-settings - 如何修复 VS Code 启动错误:bash: 意外标记附近的语法错误 `('
- javascript - 如何在 React JS 和 Firebase 中处理用户登录状态?
- javascript - 来自Android中KeyboardEvent的事件键无法识别
- javascript - 小数后精确四舍五入
- oracle - ORA-20000: APEX_INSTANCE_ADMIN_USER 无法从 Rest 管理界面启用 Rest