TP-9574 | Add cors support

This commit is contained in:
abhrajit-chattopadhyay
2022-10-01 13:28:15 +05:30
parent 71e13520ed
commit 327013791d
6 changed files with 52 additions and 37 deletions

View File

@@ -1,13 +1,16 @@
package server
import (
"fmt"
"net"
"net/http"
"strings"
"sync"
"github.com/pkg/errors"
"github.com/gorilla/mux"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/rs/cors"
)
type Server struct {
@@ -17,15 +20,14 @@ type Server struct {
}
var (
networkTCP = "tcp"
networkTCP = "tcp"
)
func NewServer(port string) (*Server, error) {
func NewServer(port string, corsList string) (*Server, error) {
network := networkTCP
listener, err := net.Listen(network, ":" + port)
listener, err := net.Listen(network, ":"+port)
if err != nil {
return nil, errors.Wrap(err, "failed to create listener")
}
@@ -42,12 +44,23 @@ func NewServer(port string) (*Server, error) {
// router.HandleFunc("/test", testHandler).Methods("GET")
// router.HandleFunc("/stop", stopHandler).Methods("POST")
httpServer := &http.Server{Addr: ":" + port, Handler: router}
httpServer := &http.Server{Addr: ":" + port, Handler: enableCors(router, corsList)}
newServer := &Server{HttpServer: httpServer, Listener: listener}
return newServer, nil
}
func enableCors(handler http.Handler, corsList string) http.Handler {
corsArray := strings.Split(corsList, ",")
fmt.Print(corsArray)
c := cors.New(cors.Options{
AllowedOrigins: corsArray,
AllowCredentials: false,
// Enable Debugging for testing, consider disabling in production
Debug: false,
})
return c.Handler(handler)
}
func MetricServer(port string) (*Server, error) {
network := networkTCP