Golang原生http实现中间件
中间件(middleware):常被用来做认证校验、审计等
- 大家常用的Iris、Gin等web框架,都包含了中间件逻辑。但有时我们引入该框架显得较为繁重,本文将介绍通过golang原生http来实现中间件操作。
- 全部代码:
https://github.com/ziyifast/ziyifast-code_instruction/tree/main/middleware
1 定义http.Handler:具体中间件操作
①CORSMiddleware:允许跨域
// CORSMiddleware handles Cross-Origin Resource Sharing (CORS) responses.
func CORSMiddleware(next http.Handler) http.Handler {
fmt.Println("cors middleware....")
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "OPTIONS" {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS, DELETE")
//如果前后端需要传递自定义请求头,需要再Access-Control-Allow-Headers中匹配(Yi-Auth-Token)
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Accept, Yi-Auth-Token")
w.WriteHeader(http.StatusOK)
return
}
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type,Accept,Yi-Auth-Token")
//交给下一个中间件处理
next.ServeHTTP(w, r)
})
}
②AuthMiddleware:认证
// AuthMiddleware simulates a simple authentication middleware.
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("auth middleware...")
//store info in ctx
token := r.Header.Get("Token")
if len(token) != 0 {
//TODO 1. check token 2. get userinfo from token
userID :=

最低0.47元/天 解锁文章
6万+

被折叠的 条评论
为什么被折叠?



