CORS,csrf 这两个的例子没看明白,暂时跳过。先看自定义中间件的例子
自定义中间件示例
代码如下:
/*
* Copyright 2022 CloudWeGo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"context"
"fmt"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/protocol/consts"
)
func MyMiddleware1() app.HandlerFunc {
return func(ctx context.Context, c *app.RequestContext) {
// pre-handle
fmt.Println("pre-handle")
}
}
func MyMiddleware2() app.HandlerFunc {
return func(ctx context.Context, c *app.RequestContext) {
// pre-handle
fmt.Println("pre-handle")
c.Next(ctx) // call the next middleware(handler)
// post-handle
fmt.Println("post-handle")
}
}
func main() {
h := server.Default(server.WithHostPorts("127.0.0.1:8080"))
h.Use(MyMiddleware1())
h.Use(MyMiddleware2())
h.GET("/middleware", func(ctx context.Context, c *app.RequestContext) {
c.String(consts.StatusOK, "Hello hertz!")
})
h.Spin()
}
这段代码里自定义了两种中间件,第一种是没法嵌套的预处理,第二种是可以形成中间件处理链的包含预处理和后处理的例子,关键是中间的 c.Next(ctx),这句让定义的中间件一个接一个的跑起来。
要运行也很简单,先跑上面这段代码,开启自定义中间件的 server:
$ go run middleware/custom/main.go
然后发送客户端的请求需要再开一个终端跑客户端的代码:
$ go run client/middleware/main.go