feat: 跨域中间件

This commit is contained in:
TsMask
2023-09-07 21:04:29 +08:00
parent 7b243bf0dd
commit 4f3878e4a2
4 changed files with 68 additions and 11 deletions

64
lib/midware/cors.go Normal file
View File

@@ -0,0 +1,64 @@
package midware
import (
"net/http"
"strings"
)
// Cors 跨域
func Cors(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 设置Vary头部
w.Header().Set("Vary", "Origin")
w.Header().Set("Keep-Alive", "timeout=5")
requestOrigin := r.Header.Get("Origin")
if requestOrigin == "" {
next.ServeHTTP(w, r)
return
}
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Credentials", "true")
// OPTIONS
if r.Method == "OPTIONS" {
requestMethod := r.Header.Get("Access-Control-Request-Method")
if requestMethod == "" {
next.ServeHTTP(w, r)
return
}
// 响应最大时间值
w.Header().Set("Access-Control-Max-Age", "31536000")
// 允许方法
allowMethods := []string{
"OPTIONS",
"HEAD",
"GET",
"POST",
"PUT",
"DELETE",
"PATCH",
}
w.Header().Set("Access-Control-Allow-Methods", strings.Join(allowMethods, ","))
// 允许请求头
allowHeaders := []string{
"Accesstoken",
}
w.Header().Set("Access-Control-Allow-Headers", strings.Join(allowHeaders, ","))
w.WriteHeader(500)
return
}
// 暴露请求头
exposeHeaders := []string{"X-RepeatSubmit-Rest", "AccessToken"}
w.Header().Set("Access-Control-Expose-Headers", strings.Join(exposeHeaders, ","))
next.ServeHTTP(w, r)
})
}

View File

@@ -37,6 +37,7 @@ func LoggerTrace(next http.Handler) http.Handler {
})
}
// 已禁用
func OptionProcess(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "OPTIONS" {
@@ -48,6 +49,7 @@ func OptionProcess(next http.Handler) http.Handler {
})
}
// 已禁用
func CheckPermission(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("AccessToken")