Golang

关注公众号 jb51net

关闭
首页 > 脚本专栏 > Golang > Golang 跨域请求

Golang 实现跨域请求的多种实现对比

作者:纸鸢666

本文主要介绍了Golang 实现跨域请求的多种实现对比,包括原生设置、第三方库、框架中间件、反向代理,具有一定的参考价值,感兴趣的可以了解一下

1. 原生 net/http 手动设置 CORS 头

通过原生库手动设置 HTTP 响应头,处理 OPTIONS 预检请求。

实现示例:

func CORS(c *gin.Context) {
	c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
	c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
	c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
	c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

	if c.Request.Method == "OPTIONS" {
		c.AbortWithStatus(http.StatusNoContent)
		return
	}

	c.Next()
}  

func main() {  
	r := gin.Default()  
	r.Use(CORS)  
  
	r.GET("/ping", func(c *gin.Context) {  
		c.JSON(200, gin.H{  
			"message": "pong",  
		})  
	})  
  
	r.Run(":8080")  
}  

优点:

缺点:

适用场景:简单项目或少量 API 端点。

2. 使用第三方库 rs/cors

通过流行的开源库 GitHub - rs/cors: Go net/http configurable handler to handle CORS requests 简化 CORS 配置。

实现示例:

package main

import (
    "net/http"
    "github.com/rs/cors"
)

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/api", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello, CORS!"))
    })

    // 配置 CORS
    c := cors.New(cors.Options{
        AllowedOrigins:   ["https://example.com", "http://localhost:3000"],
        AllowedMethods:   ["GET", "POST", "PUT", "DELETE"],
        AllowedHeaders:   ["Content-Type", "Authorization"],
        AllowCredentials: true,
        Debug:            false,
    })

    handler := c.Handler(mux)
    http.ListenAndServe(":8080", handler)
}

优点:

缺点:

适用场景:大多数项目,尤其是需要复杂 CORS 配置的情况。

3. Web 框架中间件(如 Gin、Echo)

主流 Web 框架(如 Gin、Echo)通常内置或提供 CORS 中间件。

Gin 框架示例:

package main

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

func main() {
    r := gin.Default()
    
    // 配置 CORS 中间件
    r.Use(cors.New(cors.Config{
        AllowOrigins:     ["https://example.com"],
        AllowMethods:     ["GET", "POST"],
        AllowHeaders:     ["Content-Type"],
        ExposeHeaders:    ["Content-Length"],
        AllowCredentials: true,
        MaxAge: 12 * time.Hour,
    }))
    
    r.GET("/api", func(c *gin.Context) {
        c.String(200, "Hello, CORS!")
    })
    
    r.Run(":8080")
}

优点:

缺点:

适用场景:已使用特定 Web 框架的项目。

4. 反向代理层处理(如 Nginx)

在反向代理(如 Nginx)中设置 CORS 头,无需修改 Go 代码。

Nginx 配置示例:

location /api {
    add_header 'Access-Control-Allow-Origin' 'https://example.com';
    add_header 'Access-Control-Allow-Methods' 'GET, POST';
    add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';
    
    if ($request_method = OPTIONS) {
        return 204;
    }
    
    proxy_pass http://localhost:8080;
}

优点:

缺点:

适用场景:已有反向代理层或需要统一管理 CORS 的环境。

对比与选型建议

方式维护成本灵活性依赖项适用场景
原生手动设置简单 API、快速原型
rs/cors 库中高第三方库大多数项目
Web 框架中间件框架已使用对应框架的项目
反向代理(如 Nginx)运维环境微服务、已有代理层的项目

推荐选择:

关键注意事项

通过合理选择跨域方案,可以在安全性和开发效率之间取得平衡。

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

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