概述
- echo web框架是go语言开发的一种高性能,可扩展,轻量级的web框架。echo框架真的非常简单,几行代码就可以启动一个高性能的http服务端。
- 类似python的django框架
- 可设置cookie,session,文件上传,获取用户ip等
依赖安装
go get github.com/labstack/echo/v4
go get -u github.com/swaggo/echo-swagger
go get github.com/swaggo/swag/cmd/swag
业务实操
初始化基础框架
package test_echo
import (
"fmt"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
var echoWeb *echo.Echo
var visitTotal int
func CountMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(context echo.Context) error {
visitTotal++
context.Response().Header().Add("visit-total", fmt.Sprintf("%d", visitTotal))
return next(context)
}
}
func init() {
echoWeb = echo.New()
echoWeb.Debug = true
echoWeb.Use(middleware.Recover())
echoWeb.Use(middleware.Logger())
echoWeb.Use(CountMiddleware)
}
func GetEcho() *echo.Echo {
return echoWeb
}
定义业务板块
package test_echo
import (
"github.com/labstack/echo/v4"
"net/http"
)
type HelloWorldHandler struct{}
func (receiver HelloWorldHandler) main(c echo.Context) error {
return c.String(http.StatusOK, "hello world")
}
func (receiver HelloWorldHandler) router() {
GetEcho().Add("GET", "/hello-world", receiver.main)
}
type PrintName struct{}
type PrintNameResponse struct {
Name string `json:"name"`
}
func (receiver PrintName) main(c echo.Context) error {
name := c.QueryParam("name")
return c.JSON(http.StatusOK, PrintNameResponse{Name: name})
}
func (receiver PrintName) router() {
GetEcho().Add("GET", "/print-name", receiver.main)
}
将业务与框架串联
package test_echo
import echoSwagger "github.com/swaggo/echo-swagger"
import _ "casbin-go/docs"
func SetRouter() {
HelloWorldHandler{}.router()
PrintName{}.router()
GetEcho().GET("/docs/*", echoSwagger.WrapHandler)
}
func StartRouter() {
SetRouter()
GetEcho().Start(":8080")
}
执行
package main
import (
"casbin-go/test-echo"
"fmt"
)
func echoTest() {
test_echo.StartRouter()
}
func main() {
echoTest()
}
结论
swag init
- 通过如下地址查看文档并调用接口 http://127.0.0.1:8080/docs/index.html#/
|