You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已配置CORS中间件,go-swagger生成的Swagger UI仍报跨域错误

跨域问题排查:Swagger UI调用Go Gin API时提示CORS错误

手动编写API后,后期集成go-swagger生成Swagger UI。尽管已配置CORS中间件并做过排查测试,Swagger UI仍提示API存在跨域(CORS)错误。

我的CORS中间件代码

func CORSMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        fmt.Printf("Received %s request for %s\n", c.Request.Method, c.Request.URL.Path)

        c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
        c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
        c.Writer.Header().Add("Content-Type", "application/json")
        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, access_token")
        c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")

        if c.Request.Method == "OPTIONS" {
            fmt.Println("Handling OPTIONS request")
            c.AbortWithStatus(204)
            return
        }

        c.Next()
    }
}

go-swagger API文档示例

// Package routes BARACO API.
//
//  Schemes: https
//  BasePath: /
//  Version: 1.0.0
//  Host: localhost:2443
//
//  Consumes:
//  - application/json
//
//  Produces:
//  - application/json
//
// swagger:meta
package api_docs

import "go_baraco_server/cmd/commons/models"

// swagger:parameters GetUserType
type UserTypeIDParam struct {
    // The ID of the user
    //
    // in: path
    // required: true
    ID string `json:"id"`
}

// swagger:route GET /user/{id} userTypes GetUserType
//
// GetUserType returns a userType by its ID.
//
// Responses:
//
//  200: userTypeResponse
//  400: errorResponse
func GetUserType() {}

// swagger:route GET /user_types userTypes GetUserTypes
//
// GetUserTypes returns all userTypes.
//
// Responses:
//
//  200: userTypesResponse
//  400: errorResponse
func GetUserTypes() {}

// A UserTypeResponse model
//
// swagger:response userTypeResponse
type UserTypeResponse struct {
    // The user type data
    //
    // in: body
    Item models.UserType `json:"user_type"`
}

// A AICsResponse model
//
// swagger:response userTypesResponse
type UserTypesResponse struct {
    // The user type data
    //
    // in: body
    Items []models.UserType `json:"user_types"`
}

type MinifiedUserType struct {
    // example: 355622b7-7693-4205-9b9b-86ea9313b525
    ID string `json:"id"`
    // example: Farmer
    DisplayName string `json:"display_name"`
}

Swagger UI发起的请求截图

请求截图

补充:CORS中间件在Gin框架中的实现方式

// in some gin helper module
func StartClient(conn *grpc.ClientConn) *gin.Engine {
    ginGine := gin.Default()
    ginGine.Use(CORSMiddleware())
    gin.SetMode(gin.ReleaseMode)

    //tons of api endpoint handlers
    
    //tons of StaticFS

    return ginGine
}

//in main.go
finalGin := handlers.StartClient(conn)

err := finalGin.RunTLS(fmt.Sprintf(":%v", cmmHelpers.GetConfig("HTTPS_PORT")), certFile, keyFile)
if err != nil {
    log.Fatalf("Failed to start server: %v", err)
}

内容的提问来源于stack exchange,提问作者rminaj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 07:03:16