Skip to content

Commit

Permalink
optimize: improve route demo (cloudwego#63)
Browse files Browse the repository at this point in the history
* optimize: improve route demo

* style: use gofumpt

Co-authored-by: kinggo <[email protected]>
  • Loading branch information
edufriendchen and li-jin-gou authored Dec 15, 2022
1 parent 1a4df63 commit c86a20d
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 41 deletions.
2 changes: 1 addition & 1 deletion hz_kitex_demo/hertz-server/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06 h1:1sDoSuDPWzhk
github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=
github.com/chenzhuoyu/iasm v0.0.0-20220407070608-915f5d279eca h1:zOX0dqt5KzAZfyt2tgxCZfZud+trZ5axOu8QcCkwxNY=
github.com/chenzhuoyu/iasm v0.0.0-20220407070608-915f5d279eca/go.mod h1:wOQ0nsbeOLa2awv8bUYFW/EHXbjQMlZ10fAlXDB2sz8=
github.com/choleraehyq/pid v0.0.13 h1:Tc/jYjHC50SDCxSX+DWHfMmFqtwGR8EiQ08qJ/EK8zs=
github.com/choleraehyq/pid v0.0.13/go.mod h1:uhzeFgxJZWQsZulelVQZwdASxQ9TIPZYL4TPkQMtL/U=
github.com/choleraehyq/pid v0.0.15 h1:PejhUZowqxxssjwyaw4OZURRFjnvftZfeEWK9UoWPXU=
github.com/choleraehyq/pid v0.0.15/go.mod h1:uhzeFgxJZWQsZulelVQZwdASxQ9TIPZYL4TPkQMtL/U=
Expand Down Expand Up @@ -117,6 +116,7 @@ golang.org/x/arch v0.0.0-20220412001346-fc48f9fe4c15 h1:GVfVkciLYxn5mY5EncwAe0SX
golang.org/x/arch v0.0.0-20220412001346-fc48f9fe4c15/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
Expand Down
5 changes: 4 additions & 1 deletion route/README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
# Route
You can learn about how to use hertz route:
* register route
* static route
* route group
* use middleware with route group
* parameter route
* use anonymous function or decorator to register routes
* route info

## parameter route:
Parameters such as ':name' are called `named parameters`, and named parameters only match a single path segment
Expand Down
112 changes: 73 additions & 39 deletions route/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,29 +20,41 @@ import (
"context"

"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/middlewares/server/basic_auth"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/hlog"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/protocol/consts"
)

func main() {
h := server.Default(server.WithHostPorts("127.0.0.1:8080"))

// register route
// register static route
RegisterRoute(h)

// register route with handle
RegisterRouteWithHandle(h)

// register group route
// register route group
RegisterGroupRoute(h)

// register use middleware with route group
RegisterGroupRouteWithMiddleware(h)

// register parameter route
RegisterParaRoute(h)

// register use anonymous function or decorator to register routes
RegisterAnonFunOrDecRoute(h)

// register Get route info
RegisterGetRoutesInfo(h)

h.Spin()
}

// RegisterRoute static route
func RegisterRoute(h *server.Hertz) {
h.StaticFS("/", &app.FS{Root: "./", GenerateIndexPages: true})

h.GET("/get", func(ctx context.Context, c *app.RequestContext) {
c.String(consts.StatusOK, "get")
})
Expand All @@ -64,57 +76,63 @@ func RegisterRoute(h *server.Hertz) {
h.OPTIONS("/options", func(ctx context.Context, c *app.RequestContext) {
c.String(consts.StatusOK, "options")
})
}

func RegisterRouteWithHandle(h *server.Hertz) {
h.Handle(consts.MethodGet, "/hget", func(ctx context.Context, c *app.RequestContext) {
c.String(consts.StatusOK, "hget")
h.Any("/ping_any", func(ctx context.Context, c *app.RequestContext) {
c.String(consts.StatusOK, "any")
})
h.Handle(consts.MethodPost, "/hpost", func(ctx context.Context, c *app.RequestContext) {
c.String(consts.StatusOK, "hpost")
})
h.Handle(consts.MethodPut, "/hput", func(ctx context.Context, c *app.RequestContext) {
c.String(consts.StatusOK, "hput")
})
h.Handle(consts.MethodDelete, "/hdelete", func(ctx context.Context, c *app.RequestContext) {
c.String(consts.StatusOK, "hdelete")
})
h.Handle(consts.MethodPatch, "/hpatch", func(ctx context.Context, c *app.RequestContext) {
c.String(consts.StatusOK, "hpatch")
})
h.Handle(consts.MethodHead, "/hhead", func(ctx context.Context, c *app.RequestContext) {
c.String(consts.StatusOK, "hhead")
})
h.Handle(consts.MethodOptions, "/hoptions", func(ctx context.Context, c *app.RequestContext) {
c.String(consts.StatusOK, "hoptions")
h.Handle("LOAD", "/load", func(ctx context.Context, c *app.RequestContext) {
c.String(consts.StatusOK, "load")
})
}

func loginEndpoint(ctx context.Context, c *app.RequestContext) {}

func submitEndpoint(ctx context.Context, c *app.RequestContext) {}

func readEndpoint(ctx context.Context, c *app.RequestContext) {}

// RegisterGroupRoute group route
func RegisterGroupRoute(h *server.Hertz) {
// Simple group: v1
v1 := h.Group("/v1")
{
// loginEndpoint is a handler func
v1.POST("/login", loginEndpoint)
v1.POST("/submit", submitEndpoint)
v1.POST("/streaming_read", readEndpoint)
v1.GET("/get", func(ctx context.Context, c *app.RequestContext) {
c.String(consts.StatusOK, "get")
})
v1.POST("/post", func(ctx context.Context, c *app.RequestContext) {
c.String(consts.StatusOK, "post")
})
}

// Simple group: v2
v2 := h.Group("/v2")
{
v2.POST("/login", loginEndpoint)
v2.POST("/submit", submitEndpoint)
v2.POST("/streaming_read", readEndpoint)
v2.PUT("/put", func(ctx context.Context, c *app.RequestContext) {
c.String(consts.StatusOK, "put")
})
v2.DELETE("/delete", func(ctx context.Context, c *app.RequestContext) {
c.String(consts.StatusOK, "delete")
})
}
}

// RegisterGroupRouteWithMiddleware route groups that incorporate middleware
func RegisterGroupRouteWithMiddleware(h *server.Hertz) {
// The following example uses the BasicAuth middleware in a route group.

// Sample Code 1:
//
// Bind the middleware directly to the routing group
example1 := h.Group("/example1", basic_auth.BasicAuth(map[string]string{"test": "test"}))
example1.GET("/ping", func(c context.Context, ctx *app.RequestContext) {
ctx.String(consts.StatusOK, "ping")
})

// Sample Code 2:
//
// use `Use` method
example2 := h.Group("/example2")
example2.Use(basic_auth.BasicAuth(map[string]string{"test": "test"}))
example2.GET("/ping", func(c context.Context, ctx *app.RequestContext) {
ctx.String(consts.StatusOK, "ping")
})
}

// RegisterParaRoute parameter route
func RegisterParaRoute(h *server.Hertz) {
// This handler will match: "/hertz/version", but will not match : "/hertz/" or "/hertz"
h.GET("/hertz/:version", func(ctx context.Context, c *app.RequestContext) {
Expand All @@ -136,3 +154,19 @@ func RegisterParaRoute(h *server.Hertz) {
c.String(consts.StatusOK, c.FullPath())
})
}

// RegisterAnonFunOrDecRoute Use anonymous function or decorator to register routes
func RegisterAnonFunOrDecRoute(h *server.Hertz) {
h.AnyEX("/ping", func(c context.Context, ctx *app.RequestContext) {
ctx.String(consts.StatusOK, app.GetHandlerName(ctx.Handler()))
}, "ping_handler")
}

// RegisterGetRoutesInfo Get route info
func RegisterGetRoutesInfo(h *server.Hertz) {
h.GET("/getRoutesInfo", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(consts.StatusOK, utils.H{"ping": "pong"})
})
routeInfo := h.Routes()
hlog.Info(routeInfo)
}

0 comments on commit c86a20d

Please sign in to comment.