如何在现有代码中在Go服务器上启用CORS?

问题描述 投票:0回答:1

我正在尝试在我们的服务器上启用 CORS,以便我们的 Swagger UI 可以正常运行而不会出现 CORS 错误。我无法弄清楚如何在我们的代码中实现它?

下面是来自

main.go
的代码:

package main

import (
    "context"
    "flag"
    "log"
    "net/http"
    "os"
    "os/signal"
    "time"
    "github.com/rs/cors"

    "github.com/gorilla/mux"
)

func main() {

    logFunctionFunctionName := "main.main"
    logRequestId := "MAINTHREAD"

    var wait time.Duration
    flag.DurationVar(&wait, "graceful-timeout", time.Second*7, "the duration for which the server gracefully wait for existing connections to finish - e.g. 15s or 1m")
    flag.Parse()


    configs := configurations.New(utils.CONFIG_FILE,true)
    configurations.ConfigureLog()

    configurations.PrintToLog(configurations.LogClassInformational, logRequestId, logFunctionFunctionName, "Hello Administrator!  You can gracefully shut me down via a SIGINT (Ctrl+C).  I will then wait 15 seconds for my users requests to finish.")

    configurations.PrintToLog(configurations.LogClassInformational, logRequestId, logFunctionFunctionName,
        "API's running 0.0.11 minor 3 20191010 3:00 pm ")

    r := mux.NewRouter().StrictSlash(true)

    createRoutes(r)

    srv := &http.Server{
        Addr: configs.ThisPortNumber,
        
        Handler: r, 
    }

    go func() {

        if err := srv.ListenAndServe(); err != nil {
            log.Println(err)
        }

    }()

    c := make(chan os.Signal, 1)
    
    signal.Notify(c, os.Interrupt)

    <-c

    ctx, cancel := context.WithTimeout(context.Background(), wait)
    defer cancel()
    
    srv.Shutdown(ctx)
    
    configurations.PrintToLog(configurations.LogClassInformational, logRequestId, logFunctionFunctionName, "shutting down")
    os.Exit(0)

}

下面是来自

routes.go
的代码:

package main

import (
    
    "strings"

    "net/http"
    "github.com/gorilla/mux"
)



func AddHandlers(r *mux.Router) {
        handleGetSwaggerDocs(r)
    }
    
func handleGetSwaggerDocs(r *mux.Router) {
        fs := http.FileServer(http.Dir("./swagger/"))
        r.PathPrefix("/swagger/").Handler(http.StripPrefix("/swagger/", fs)).Name("swagger")
        http.Handle("/swagger/", r)
    }   

func createRoutes(r *mux.Router) *mux.Router {
        

        r.HandleFunc("/api/v{versionNbr}/EMPAPI", api.GetEMPAPI).Methods("GET")
    
    AddHandlers(r)
    return r
}

尝试弄清楚如何实现 CORS 启用代码。

go cors swagger-ui
1个回答
0
投票

我们目前使用的是 Go 1.20。这就是我尝试启用 cors 的方法,但是在 swagger ui 上,我仍然遇到无法获取错误。当尝试检查开发人员工具时,它清楚地表明从源“crossaccumsapi.ckp-dev.aws.centene.com”获取的访问已被 CORS 策略阻止:没有“Access-Control-Allow-Origin”标头存在所请求的资源。如果不透明响应满足您的需求,请将请求模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。即使卷曲请求也没有附加允许的起源标头

包主

导入( “语境” “旗帜” “日志” “网络/http” “操作系统” “操作系统/信号” “时间”

"github.com/gorilla/handlers"
"github.com/gorilla/mux"

func main() {

logFunctionFunctionName := "main.main"
logRequestId := "MAINTHREAD"

var wait time.Duration
flag.DurationVar(&wait, "graceful-timeout", time.Second*7, "the duration for which the server gracefully wait for existing connections to finish - e.g. 15s or 1m")
flag.Parse()

configs := configurations.New(utils.CONFIG_FILE,true)
configurations.ConfigureLog()

configurations.PrintToLog(configurations.LogClassInformational, logRequestId, logFunctionFunctionName, "Hello Administrator!  You can gracefully shut me down via a SIGINT (Ctrl+C).  I will then wait 15 seconds for my users requests to finish.")

configurations.PrintToLog(configurations.LogClassInformational, logRequestId, logFunctionFunctionName,
    "API's running 0.0.11 minor 3 20191010 3:00 pm ")

r := mux.NewRouter().StrictSlash(true)


createRoutes(r)

corsOptions := handlers.AllowedOrigins([]string{"*"})  
corsHandler := handlers.CORS(corsOptions)(r)

srv := &http.Server{
    Addr: configs.ThisPortNumber,
    Handler: corsHandler, 
}

// Run our server in a goroutine so that it doesn't block.
go func() {

    if err := srv.ListenAndServe(); err != nil {
        log.Println(err)
    }

}()

c := make(chan os.Signal, 1)

signal.Notify(c, os.Interrupt)


<-c


ctx, cancel := context.WithTimeout(context.Background(), wait)
defer cancel()

srv.Shutdown(ctx)

configurations.PrintToLog(configurations.LogClassInformational, logRequestId, logFunctionFunctionName, "shutting down")
os.Exit(0)

}

© www.soinside.com 2019 - 2024. All rights reserved.