2019-03-01 23:45:55 +08:00
|
|
|
// Copyright 2019 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
|
|
|
//
|
|
|
|
// This Source Code Form is subject to the terms of the MIT License.
|
|
|
|
// If a copy of the MIT was not distributed with this file,
|
|
|
|
// You can obtain one at https://github.com/gogf/gf.
|
|
|
|
//
|
|
|
|
|
|
|
|
package ghttp
|
|
|
|
|
|
|
|
import (
|
2019-06-19 09:06:52 +08:00
|
|
|
"github.com/gogf/gf/g/util/gconv"
|
2019-03-01 23:45:55 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
// See https://www.w3.org/TR/cors/ .
|
|
|
|
// 服务端允许跨域请求选项
|
|
|
|
type CORSOptions struct {
|
2019-06-19 09:06:52 +08:00
|
|
|
AllowOrigin string // Access-Control-Allow-Origin
|
|
|
|
AllowCredentials string // Access-Control-Allow-Credentials
|
|
|
|
ExposeHeaders string // Access-Control-Expose-Headers
|
|
|
|
MaxAge int // Access-Control-Max-Age
|
|
|
|
AllowMethods string // Access-Control-Allow-Methods
|
|
|
|
AllowHeaders string // Access-Control-Allow-Headers
|
2019-03-01 23:45:55 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// 默认的CORS配置
|
|
|
|
func (r *Response) DefaultCORSOptions() CORSOptions {
|
2019-06-19 09:06:52 +08:00
|
|
|
return CORSOptions{
|
2019-06-24 19:05:07 +08:00
|
|
|
AllowOrigin: "*",
|
2019-06-19 09:06:52 +08:00
|
|
|
AllowMethods: HTTP_METHODS,
|
|
|
|
AllowCredentials: "true",
|
|
|
|
MaxAge: 3628800,
|
|
|
|
}
|
2019-03-01 23:45:55 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// See https://www.w3.org/TR/cors/ .
|
|
|
|
// 允许请求跨域访问.
|
|
|
|
func (r *Response) CORS(options CORSOptions) {
|
2019-06-19 09:06:52 +08:00
|
|
|
if options.AllowOrigin != "" {
|
|
|
|
r.Header().Set("Access-Control-Allow-Origin", options.AllowOrigin)
|
|
|
|
}
|
|
|
|
if options.AllowCredentials != "" {
|
|
|
|
r.Header().Set("Access-Control-Allow-Credentials", options.AllowCredentials)
|
|
|
|
}
|
|
|
|
if options.ExposeHeaders != "" {
|
|
|
|
r.Header().Set("Access-Control-Expose-Headers", options.ExposeHeaders)
|
|
|
|
}
|
|
|
|
if options.MaxAge != 0 {
|
|
|
|
r.Header().Set("Access-Control-Max-Age", gconv.String(options.MaxAge))
|
|
|
|
}
|
|
|
|
if options.AllowMethods != "" {
|
|
|
|
r.Header().Set("Access-Control-Allow-Methods", options.AllowMethods)
|
|
|
|
}
|
|
|
|
if options.AllowHeaders != "" {
|
|
|
|
r.Header().Set("Access-Control-Allow-Headers", options.AllowHeaders)
|
|
|
|
}
|
2019-03-01 23:45:55 +08:00
|
|
|
}
|
|
|
|
|
2019-03-31 20:52:30 +08:00
|
|
|
// 允许请求跨域访问(使用默认配置).
|
2019-03-01 23:45:55 +08:00
|
|
|
func (r *Response) CORSDefault() {
|
2019-06-19 09:06:52 +08:00
|
|
|
r.CORS(r.DefaultCORSOptions())
|
2019-03-01 23:45:55 +08:00
|
|
|
}
|