22 lines
669 B
Go
22 lines
669 B
Go
|
package middleware
|
||
|
|
||
|
import "net/http"
|
||
|
|
||
|
// CorsMiddleware 是处理跨域请求的中间件
|
||
|
func CorsMiddleware(next http.Handler) http.Handler {
|
||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||
|
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
||
|
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-CSRF-Token")
|
||
|
w.Header().Set("Access-Control-Expose-Headers", "Content-Length, X-CSRF-Token")
|
||
|
|
||
|
// 处理预检请求
|
||
|
if r.Method == http.MethodOptions {
|
||
|
w.WriteHeader(http.StatusOK)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
next.ServeHTTP(w, r)
|
||
|
})
|
||
|
}
|