官方文档

Echo 入门示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package main

import (
    "net/http"
    "github.com/labstack/echo/v4"
    "github.com/labstack/echo/v4/middleware"
)

func main() {
    // Echo instance
    e := echo.New()

    // Middleware
    e.Use(middleware.Logger())
    e.Use(middleware.Recover())

    e.Use(middleware.BodyLimit("1M")) // 限制http请求body大小,不设置默认无限制

    // Routes
    e.GET("/", hello)

    // Start server
    // e.Logger.Fatal(e.Start(":1323"))

    // 平滑关闭,关闭服务前会等待所有http请求结束
    if err := e.Start(":1323"); err != nil && err != http.ErrServerClosed {
        log.Println(err)
    }
}

// Handler
func hello(c echo.Context) error {
    // return c.String(http.StatusOK, "Hello, World!")
    return c.JSON(http.StatusBadRequest, response.Success(err.Error()))
}

路由分组

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
type NoticeController struct{}

var noticeController = &NoticeController{}

var Route = echo.New()

notice := Router.Group("/notice", noticeAuthMiddleware)

// 列表
notice.GET("", noticeController.getList)

// 新建
notice.POST("", noticeController.createNotice)

// 编辑
notice.PUT("/:id", noticeController.updateNotice)

// 删除
notice.DELETE("/:id", noticeController.deleteNotice)

context

1
2
3
4
// 获取上下文
req := httptest.NewRequest(http.MethodGet, "/url/xxx", nil)
resp := httptest.NewRecorder()
ctx := Echo.NewContext(req, resp)

其他

echo path 之分

  • c.Path() :注册路由,动态路由
  • c.Request().URL.Path 请求路由,静态路由

c.QueryString(): 获取uri上的请求参数

获取请求body

1
2
3
4
func GetReqBody(c echo.Context) {
    requestBody, _ := ioutil.ReadAll(c.Request().Body)
    fmt.Println("uri=%s, req body=%s", c.Request().RequestURI, string(requestBody))
}

获取请求Header参数

c.Request().Header.Get(“token”)

设置并获取上下文参数

c.Set(“user”, user) user, _ := c.Get(“user”).(model.User)

获取 uri 上的 query 参数

id, _ := strconv.ParseUint(c.Param(“id”), 10, 64)

在Echo中使用pprof

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import _ "net/http/pprof"

func RegisterRoutes(engine *echo.Echo) {
    router := engine.Group("")
    ......
    // 下面的路由根据要采集的数据需求注册,不用全都注册
    router.GET("/debug/pprof", echo.WrapHandler(http.HandlerFunc(pprof.Index)))
    router.GET("/debug/pprof/allocs", echo.WrapHandler(http.HandlerFunc(pprof.Index)))
    router.GET("/debug/pprof/block", echo.WrapHandler(http.HandlerFunc(pprof.Index)))
    router.GET("/debug/pprof/goroutine", echo.WrapHandler(http.HandlerFunc(pprof.Index)))
    router.GET("/debug/pprof/heap", echo.WrapHandler(http.HandlerFunc(pprof.Index)))
    router.GET("/debug/pprof/mutex", echo.WrapHandler(http.HandlerFunc(pprof.Index)))
    router.GET("/debug/pprof/cmdline", echo.WrapHandler(http.HandlerFunc(pprof.Cmdline)))
    router.GET("/debug/pprof/profile", echo.WrapHandler(http.HandlerFunc(pprof.Profile)))
    router.GET("/debug/pprof/symbol", echo.WrapHandler(http.HandlerFunc(pprof.Symbol)))
    router.GET("/debug/pprof/trace", echo.WrapHandler(http.HandlerFunc(pprof.Trace)))
}

导出文件

1
2
3
4
resp := []byte{} // 文件内容
filename := fmt.Sprintf("code_%s.xlsx", time.Now().Format("2006-01-02 15:04:05"))
c.Response().Header().Set(echo.HeaderContentDisposition, "attachment; filename="+filename)
return c.Stream(http.StatusOK, echo.MIMEOctetStream, bytes.NewReader(resp))

websocket

websocket example