Search code examples
gogorillamux

How can I allow CORS using many ports?


I came across this code and would like to allow CORS on port 1111,1112 and 1113 how can I do that?

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

In this example, CORS is listening only on port 1111, so I would like to add more ports, please any help?


Solution

  • Put them in separate go routines:

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