github.com/zhongdalu/gf@v1.0.0/g/net/ghttp/ghttp_response_cors.go (about) 1 // Copyright 2019 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/zhongdalu/gf. 6 // 7 8 package ghttp 9 10 import ( 11 "github.com/zhongdalu/gf/g/util/gconv" 12 ) 13 14 // See https://www.w3.org/TR/cors/ . 15 // 服务端允许跨域请求选项 16 type CORSOptions struct { 17 AllowOrigin string // Access-Control-Allow-Origin 18 AllowCredentials string // Access-Control-Allow-Credentials 19 ExposeHeaders string // Access-Control-Expose-Headers 20 MaxAge int // Access-Control-Max-Age 21 AllowMethods string // Access-Control-Allow-Methods 22 AllowHeaders string // Access-Control-Allow-Headers 23 } 24 25 // 默认的CORS配置 26 func (r *Response) DefaultCORSOptions() CORSOptions { 27 return CORSOptions{ 28 AllowOrigin: "*", 29 AllowMethods: HTTP_METHODS, 30 AllowCredentials: "true", 31 MaxAge: 3628800, 32 } 33 } 34 35 // See https://www.w3.org/TR/cors/ . 36 // 允许请求跨域访问. 37 func (r *Response) CORS(options CORSOptions) { 38 if options.AllowOrigin != "" { 39 r.Header().Set("Access-Control-Allow-Origin", options.AllowOrigin) 40 } 41 if options.AllowCredentials != "" { 42 r.Header().Set("Access-Control-Allow-Credentials", options.AllowCredentials) 43 } 44 if options.ExposeHeaders != "" { 45 r.Header().Set("Access-Control-Expose-Headers", options.ExposeHeaders) 46 } 47 if options.MaxAge != 0 { 48 r.Header().Set("Access-Control-Max-Age", gconv.String(options.MaxAge)) 49 } 50 if options.AllowMethods != "" { 51 r.Header().Set("Access-Control-Allow-Methods", options.AllowMethods) 52 } 53 if options.AllowHeaders != "" { 54 r.Header().Set("Access-Control-Allow-Headers", options.AllowHeaders) 55 } 56 } 57 58 // 允许请求跨域访问(使用默认配置). 59 func (r *Response) CORSDefault() { 60 r.CORS(r.DefaultCORSOptions()) 61 }