Golang

关注公众号 jb51net

关闭
首页 > 脚本专栏 > Golang > Golang 跨域资源共享

Golang多个域名的跨域资源共享的实现

作者:gskyi

本文主要介绍了Golang多个域名的跨域资源共享的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

在 Golang 中,处理多个域名的跨域资源共享 (CORS) 可以通过动态检查 Origin 并设置响应头来实现。以下是基于 Golang 的实现示例。

1. 动态判断域名并设置 CORS

根据请求的 Origin,判断是否允许,并动态设置 Access-Control-Allow-Origin

示例代码

package main

import (
	"net/http"
)

func main() {
	allowedOrigins := []string{
		"https://example1.com",
		"https://example2.com",
		"https://example3.com",
	}

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		origin := r.Header.Get("Origin")
		for _, o := range allowedOrigins {
			if origin == o {
				w.Header().Set("Access-Control-Allow-Origin", origin)
				w.Header().Set("Access-Control-Allow-Credentials", "true")
				w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
				w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
				break
			}
		}

		// Handle preflight request
		if r.Method == http.MethodOptions {
			w.WriteHeader(http.StatusNoContent)
			return
		}

		// Example response for other requests
		w.Write([]byte("CORS configured!"))
	})

	http.ListenAndServe(":8080", nil)
}

2. 使用第三方库 (Gin 框架)

如果使用 Gin,可以通过中间件实现动态域名的 CORS。

示例代码

package main

import (
	"github.com/gin-gonic/gin"
)

func main() {
	allowedOrigins := []string{
		"https://example1.com",
		"https://example2.com",
		"https://example3.com",
	}

	r := gin.Default()

	// 自定义中间件处理 CORS
	r.Use(func(c *gin.Context) {
		origin := c.Request.Header.Get("Origin")
		for _, o := range allowedOrigins {
			if origin == o {
				c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
				c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
				c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
				c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
				break
			}
		}

		// 如果是 OPTIONS 请求,提前返回
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	})

	r.GET("/", func(c *gin.Context) {
		c.JSON(200, gin.H{"message": "CORS configured!"})
	})

	r.Run(":8080")
}

3. Nginx 配合 Golang 实现多个域名 CORS

如果使用 Nginx 作为反向代理,CORS 的域名过滤可以在 Nginx 层处理。具体配置如下:

示例 Nginx 配置

server {
    listen 80;
    server_name yourdomain.com;

    location / {
        set $cors "";
        if ($http_origin ~* "(https://example1\.com|https://example2\.com|https://example3\.com)") {
            set $cors $http_origin;
        }
        add_header Access-Control-Allow-Origin $cors;
        add_header Access-Control-Allow-Credentials true;
        add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
        add_header Access-Control-Allow-Headers "Content-Type, Authorization";

        # Pass the request to your Golang app
        proxy_pass http://127.0.0.1:8080;
    }
}

注意事项

 到此这篇关于Golang多个域名的跨域资源共享的实现的文章就介绍到这了,更多相关Golang 跨域资源共享内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文