百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
C

cors

> 编程语言
开源

官方 CORS gin 中间件

2.0K stars0 点赞0 次浏览
访问官网GitHub

工具介绍

官方 CORS gin 中间件

gin-contrib/cors

  • gin-contrib/cors
    • 概述
    • 安装
    • 快速入门
    • 高级用法
      • 自定义配置
      • DefaultConfig 参考
      • Default() 便利方法
    • 配置参考
      • 配置注意事项
      • 示例
        • 高级选项
        • 自定义源验证
        • 与 Gin 上下文一起使用
    • 辅助方法
    • 验证与错误处理
    • 重要注意事项

概述

CORS (Cross-Origin Resource Sharing) 中间件用于 Gin。

  • 为基于 Gin 的 API 提供灵活的 CORS 处理。
  • 可高度配置: 来源、方法、头部、凭据等。

安装

bash
go get github.com/gin-contrib/cors

在 Go 代码中导入:

go
import "github.com/gin-contrib/cors"

快速入门

允许所有来源(默认):

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

func main() {
  router := gin.Default()
  router.Use(cors.Default()) // All origins allowed by default
  router.Run()
}

⚠️ 警告: 允许所有来源会禁用客户端的 Cookie。对于具有凭证的请求,请不要 允许所有来源。


高级用法

自定义配置

配置允许的源、方法、头等内容:

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

func main() {
  router := gin.Default()
  router.Use(cors.New(cors.Config{
    AllowOrigins:     []string{"https://foo.com"},
    AllowMethods:     []string{"PUT", "PATCH"},
    AllowHeaders:     []string{"Origin"},
    ExposeHeaders:    []string{"Content-Length"},
    AllowCredentials: true,
    AllowOriginFunc: func(origin string) bool {
      return origin == "https://github.com"
    },
    MaxAge: 12 * time.Hour,
  }))
  router.Run()
}

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Go

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言