登录
首页 >  Golang >  Go问答

允许跨源资源共享(CORS)使用多个端口的方法

来源:stackoverflow

时间:2024-02-19 18:45:19 415浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《允许跨源资源共享(CORS)使用多个端口的方法》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我遇到了这段代码,希望在端口 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))

以上就是《允许跨源资源共享(CORS)使用多个端口的方法》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>