【问题标题】:How can I allow CORS using many ports?如何允许 CORS 使用多个端口?
【发布时间】:2020-09-27 05:37:57
【问题描述】:

我遇到了这段代码,想在端口 1111、1112 和 1113 上允许 CORS,我该怎么做?

router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/all", All).Methods("GET")
router.HandleFunc("/gotoT", Goto).Methods("GET")
headers := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization"})
methods := handlers.AllowedMethods([]string{"GET", "POST", "PUT", "HEAD", "OPTIONS"})
origins := handlers.AllowedOrigins([]string{"*"})
log.Fatal(http.ListenAndServe(":1111", handlers.CORS(headers, methods, origins)(router)))

在这个例子中,CORS 只监听端口 1111所以我想添加更多端口,请帮忙?

【问题讨论】:

  • 在本例中,http-server 正在监听端口 1111。您希望同一台服务器同时在不同端口上运行吗?也许端口转发是一个更好的主意。

标签: go gorilla mux


【解决方案1】:

将它们放在单独的 goroutines 中:

router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/all", All).Methods("GET")
router.HandleFunc("/gotoT", Goto).Methods("GET")
headers := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization"})
methods := handlers.AllowedMethods([]string{"GET", "POST", "PUT", "HEAD", "OPTIONS"})
origins := handlers.AllowedOrigins([]string{"*"})

corsRouter := handlers.CORS(headers, methods, origins)(router)

go func() {
    log.Fatal(http.ListenAndServe(":1111", corsRouter))
}()

go func() {
    log.Fatal(http.ListenAndServe(":1112", corsRouter))
}()

log.Fatal(http.ListenAndServe(":1113", corsRouter))

【讨论】:

    猜你喜欢
    • 2022-09-28
    • 1970-01-01
    • 2018-04-07
    • 2015-07-19
    • 2017-11-23
    • 2016-06-08
    • 1970-01-01
    • 2020-08-14
    • 1970-01-01
    相关资源
    最近更新 更多