go - 创建路由模块 Go/Echo RestAPI

标签 go go-echo

我刚开始学习 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,当然仍然有一些语法错误,会解决它们,但我目前正在为我的代码架构而苦苦挣扎。

最佳答案

I want to have the routes of my api in a different file for example: routes/users.go that then I include in the "main" function and register those routes.

这是可能的,只需让 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 示例的首字母为小写。这是因为首字母小写的标识符未导出,这使得它们无法从自己的包外部访问。换句话说,为了能够引用导入的标识符,您必须通过以大写字母开头来导出它。

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

关于go - 创建路由模块 Go/Echo RestAPI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57595608/

相关文章:

go - 如何将日期字符串绑定(bind)到结构?

Golang Echo Labstack 如何在模板 View 中调用函数/方法

go - 带有/代理中间件的 Echo CORS 会导致/Access-Allow-Origins 响应 header 出现问题

go - 似乎无法开始使用 Go 和 Echo

go - 当用 * 实例化 var 时,单例测试不起作用

go - 在 Echo/Go 上实现特定路线超时的最佳方法

go - 使用指针和接口(interface)以及自定义类型

macos - 什么是 macbook 网络摄像头的正确路径

ajax - 如何使用ajax从go api检索数据?

go - 如何读取包含波浪号的文件/路径