go - 如何允许CORS使用多个端口?

标签 go gorilla mux

我遇到了此代码,并希望在端口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 上监听,因此我想添加更多端口,请帮忙吗?

最佳答案

将它们放在单独的go例程中:

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))

关于go - 如何允许CORS使用多个端口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64085188/

相关文章:

go - 如何将不同类型作为 struct{} 传递给 GoLang 函数?

go - 根据请求处理 XMLFile

Golang websocket客户端,获取结果后关闭连接

go - 将参数传递给 golang 中的 mux 处理程序函数

reactjs - 如何设置服务 reactjs 应用程序的路由?

Goland显示os.Remove()无法解决?

web - 在抓取完整的纽约时报文章时如何规避机器人保护?

API 设计 - 一个域上的应用程序,不同域上的 api。如何在不传递用户 ID 的情况下检索用户特定数据

go - 即使使用 SkipClean 后也不接受双斜线

Golang gorilla mux 未找到处理程序无法正常工作