增加CORS自适应跨域

This commit is contained in:
刘祥超
2022-12-29 17:16:42 +08:00
parent c4bac7f43c
commit e87f031293

View File

@@ -1556,7 +1556,7 @@ func (this *HTTPRequest) processRequestHeaders(reqHeader http.Header) {
}
// 是否已删除
if this.web.ResponseHeaderPolicy.ContainsDeletedHeader(header.Name) {
if this.web.RequestHeaderPolicy.ContainsDeletedHeader(header.Name) {
continue
}
@@ -1694,6 +1694,36 @@ func (this *HTTPRequest) processResponseHeaders(responseHeader http.Header, stat
responseHeader[header.Name] = []string{headerValue}
}
}
// CORS
if this.web.ResponseHeaderPolicy.CORS != nil && this.web.ResponseHeaderPolicy.CORS.IsOn {
var corsConfig = this.web.ResponseHeaderPolicy.CORS
// Allow-Origin
if len(corsConfig.AllowOrigin) == 0 {
var origin = this.RawReq.Header.Get("Origin")
if len(origin) > 0 {
responseHeader.Set("Access-Control-Allow-Origin", origin)
}
} else {
responseHeader.Set("Access-Control-Allow-Origin", corsConfig.AllowOrigin)
}
// Allow-Methods
if len(corsConfig.AllowMethods) == 0 {
responseHeader.Set("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, HEAD, OPTIONS")
} else {
responseHeader.Set("Access-Control-Allow-Methods", strings.Join(corsConfig.AllowMethods, ", "))
}
// Max-Age
if corsConfig.MaxAge > 0 {
responseHeader.Set("Access-Control-Max-Age", types.String(corsConfig.MaxAge))
}
// Allow-Credentials
responseHeader.Set("Access-Control-Allow-Credentials", "true")
}
}
// HSTS