在Golang中实现多个域名的跨域资源共享(CORS, Cross-Origin Resource Sharing)通常涉及设置适当的HTTP响应头,以告知浏览器允许来自不同源的请求。以下是一个基本的实现步骤,适用于使用标准库或流行Web框架(如Gin、Echo等)的Golang应用。
![图片[1]_在Golang应用中配置多域名跨域资源共享(CORS)_知途无界](https://zhituwujie.com/wp-content/uploads/2025/02/d2b5ca33bd20250217101342.png)
使用标准库实现CORS
如果你没有使用任何Web框架,你可以手动设置CORS头。以下是一个简单的例子:
package main
import (
"fmt"
"net/http"
"strings"
)
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 允许的域名列表,可以根据需要动态设置
allowedOrigins := []string{"https://example1.com", "https://example2.com"}
origin := r.Header.Get("Origin")
// 检查请求的Origin是否在允许的列表中
if origin != "" && !contains(allowedOrigins, origin) {
http.Error(w, "Origin not allowed", http.StatusForbidden)
return
}
// 设置CORS头
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
w.Header().Set("Access-Control-Allow-Credentials", "true")
// 对于预检请求(OPTIONS),直接返回204状态码
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusNoContent)
return
}
// 调用下一个处理器
next.ServeHTTP(w, r)
})
}
func contains(slice []string, item string) bool {
for _, v := range slice {
if v == item {
return true
}
}
return false
}
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", helloHandler)
// 使用CORS中间件包装mux
handler := corsMiddleware(mux)
http.ListenAndServe(":8080", handler)
}
使用Gin框架实现CORS
如果你使用Gin框架,你可以使用github.com/gin-contrib/cors
中间件:
package main
import (
"github.com/gin-gonic/gin"
"github.com/gin-contrib/cors"
)
func main() {
r := gin.Default()
// 配置CORS中间件
// 允许的域名列表,可以根据需要动态设置
allowedOrigins := []string{"https://example1.com", "https://example2.com"}
corsConfig := cors.DefaultConfig()
corsConfig.AllowOrigins = allowedOrigins
corsConfig.AllowMethods = []string{"GET", "POST", "OPTIONS", "PUT", "DELETE"}
corsConfig.AllowHeaders = []string{"Accept", "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization"}
corsConfig.AllowCredentials = true
r.Use(cors.New(corsConfig))
r.GET("/", func(c *gin.Context) {
c.String(200, "Hello, World!")
})
r.Run(":8080")
}
注意事项
- 安全性:只允许你信任的域名进行跨域请求。
- 凭据:如果设置了
Access-Control-Allow-Credentials
为true
,则Access-Control-Allow-Origin
不能设置为*
,必须是指定的域名。 - 预检请求:对于复杂请求(如使用
PUT
、DELETE
方法或发送自定义头),浏览器会首先发送一个OPTIONS
请求作为预检。你的服务器需要正确处理这些预检请求。 - 动态配置:在实际应用中,你可能需要根据数据库或配置文件动态地设置允许的域名列表。
通过上述方法,你可以在Golang应用中实现多个域名的跨域资源共享。
© 版权声明
文中内容均来源于公开资料,受限于信息的时效性和复杂性,可能存在误差或遗漏。我们已尽力确保内容的准确性,但对于因信息变更或错误导致的任何后果,本站不承担任何责任。如需引用本文内容,请注明出处并尊重原作者的版权。
THE END
暂无评论内容