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

时间:2024-02-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学习网公众号!

本文内容来源于互联网,如有侵权请联系删除。

相关文章

更多

热门专题

更多
首页