在Golang应用中配置多域名跨域资源共享(CORS)

在Golang中实现多个域名的跨域资源共享(CORS, Cross-Origin Resource Sharing)通常涉及设置适当的HTTP响应头,以告知浏览器允许来自不同源的请求。以下是一个基本的实现步骤,适用于使用标准库或流行Web框架(如Gin、Echo等)的Golang应用。

图片[1]_在Golang应用中配置多域名跨域资源共享(CORS)_知途无界

使用标准库实现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")
}

注意事项

  1. 安全性:只允许你信任的域名进行跨域请求。
  2. 凭据:如果设置了Access-Control-Allow-Credentialstrue,则Access-Control-Allow-Origin不能设置为*,必须是指定的域名。
  3. 预检请求:对于复杂请求(如使用PUTDELETE方法或发送自定义头),浏览器会首先发送一个OPTIONS请求作为预检。你的服务器需要正确处理这些预检请求。
  4. 动态配置:在实际应用中,你可能需要根据数据库或配置文件动态地设置允许的域名列表。

通过上述方法,你可以在Golang应用中实现多个域名的跨域资源共享。

© 版权声明
THE END
喜欢就点个赞,支持一下吧!
点赞34 分享
评论 抢沙发
头像
欢迎您留下评论!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容