控制器是用来处理访问地址具体逻辑的,我们在开发具体的应用的时候,要将控制器放在不同的文件不同的目录。
原先我们访问 /hello 路由与逻辑一起,现在我们要把路由跟逻辑拆出来。项目结构也进行调整。
e.GET("/hello", func(c echo.Context) error { return c.String(http.StatusOK, "Hello, World!") })
一、hello.ctrl.go
写完控制器,要在路由加上
package indexIndex import ( "net/http" "github.com/labstack/echo/v4" ) /*@@HelloIndex@@*/ func HelloIndex(c echo.Context) (err error) { reData := make(map[string]interface{}) name := c.QueryParam("name") reData["name"] = name reJson := make(map[string]interface{}) reJson["error"] = 0 reJson["message"] = "success" reJson["data"] = reData return c.JSON(http.StatusOK, reJson) } func HelloMy(){} func HelloUser(){}
e.GET("/hello/index", indexIndex.HelloIndex)
二、request 请求
name := c.Param("name") //path hello/:name name := c.QueryParam("name") //url hello?name:a name := c.FormValue("name") //form
三、response 输出
c.String(http.StatusOK, "Hello, World!") c.HTML(http.StatusOK, "<strong>Hello, World!</strong>") c.JSON(http.StatusOK, reJson)