使用go echo 作为http 服务器,为了减少不必要的路由注册功能,实现了controller来约束用户,达到自动注册的目的; 使用反射实现路由注册;
e.POST("/users", saveUser)
e.GET("/users/:id", getUser)
e.PUT("/users/:id", updateUser)
e.DELETE("/users/:id", deleteUser)
main.go
package main
import (
"log"
"os"
_ "github.com/xsean2020/go-web-server/example/docs" // docs is generated by Swag CLI, you have to import it.
"github.com/xsean2020/go-web-server/router" // docs is generated by Swag CLI, you have to import it.
echo "github.com/labstack/echo/v4"
cli "github.com/urfave/cli/v2"
)
// @title Swagger Example API
// @version 1.0
// @description This is a sample server Petstore server.
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email [email protected]
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host petstore.swagger.io
// @BasePath /v2/api
func main() {
log.Println((&cli.App{
Name: "echo-server",
Usage: "server",
Version: "v1.0.0",
HideVersion: true,
Description: "wrap for echo server",
Authors: []*cli.Author{},
Flags: []cli.Flag{
&cli.StringFlag{Name: "config", Aliases: []string{"c"}, Value: "config.yaml", Usage: "config file"},
},
Action: func(c *cli.Context) error {
e := echo.New()
router.BuildEchoRouter(e)
return e.Start(":8080")
},
}).Run(os.Args))
}
import (
"net/http"
"github.com/xsean2020/go-web-server/router" // docs is generated by Swag CLI, you have to import it.
echo "github.com/labstack/echo/v4"
)
// Demo for controller
func init() {
// 全局注册到srv 中,自动生成路由规则
router.Register(&HellWorld{})
}
type HellWorld struct{}
// 替换 uri 生成规则
// 使用自定义的path 代替程序自动生成的
// 方法名子不缺粉大小写
func (c *HellWorld) Alias() map[string]string {
return map[string]string{"get_hello_work": "/hello"}
}
// controller 需要单独使用的中间件
func (c *HellWorld) Middlewares() []echo.MiddlewareFunc {
return nil
}
// URI 前缀
func (c *HellWorld) Group() string {
return "/api/v2"
}
// GET /api/v2/hello
// 等价于 e.GET("/api/v2/hello", Hello)
func (c *HellWorld) Hello(cc echo.Context) error {
return cc.JSON(http.StatusOK, struct{ Msg string }{"HellWorld"})
}
// POST /api/v2/id
// 等价于 e.POST("/api/v2/:id", POST__id)
func (c *HellWorld) POST__id(cc echo.Context) error {
return cc.JSON(http.StatusOK, struct{ Msg string }{"HellWorld"})
}
// GET /api/v2/id
// 等价于 e.GET("/api/v2/id", GET_id)
func (c *HellWorld) GET_id(cc echo.Context) error {
return cc.JSON(http.StatusOK, struct{ Msg string }{"HellWorld"})
}
// GET /api/v2/:user/:id
// 等价于 e.GET("/:user/:id", Get__user__id)
func (c *HellWorld) Get__user__id(cc echo.Context) error {
return cc.JSON(http.StatusOK, struct{ Msg string }{"HellWorld"})
}