func main() { // Create a REST API handler api := rest.New() // Add a resource on /users[/:user_id] users := api.Bind("users", rest.NewResource(user, mem.NewHandler(), rest.Conf{ // We allow all REST methods // (rest.ReadWrite is a shortcut for []rest.Mode{Create, Read, Update, Delete, List}) AllowedModes: rest.ReadWrite, })) // Bind a sub resource on /users/:user_id/posts[/:post_id] // and reference the user on each post using the "user" field of the posts resource. posts := users.Bind("posts", "user", rest.NewResource(post, mem.NewHandler(), rest.Conf{ // Posts can only be read, created and deleted, not updated AllowedModes: []rest.Mode{rest.Read, rest.List, rest.Create, rest.Delete}, })) // Add a friendly alias to public posts // (equivalent to /users/:user_id/posts?filter=public=true) posts.Alias("public", url.Values{"filter": []string{"public=true"}}) // Add cors support h := cors.New(cors.Options{OptionsPassthrough: true}).Handler(api) // Bind the API under /api/ path http.Handle("/api/", http.StripPrefix("/api/", h)) // Serve it log.Print("Serving API on http://localhost:8080") if err := http.ListenAndServe(":8080", nil); err != nil { log.Fatal(err) } }
func main() { r := mux.NewRouter().StrictSlash(true) var mgoConn = os.Getenv("MGOCONN") if mgoConn == "" { log.Fatal("No connection string found.") } log.Println(mgoConn) db := db.NewDatabase(mgoConn, "house") tc := controllers.NewTransactionController(db) hc := controllers.NewHomeController() r.HandleFunc("/", hc.HomeHandler).Methods("GET") r.HandleFunc("/transactions", tc.GetTransactionsHandler).Methods("GET") r.HandleFunc("/transactions/{id}", tc.GetTransactionHandler).Methods("GET") r.HandleFunc("/transactions", tc.PostTransactionHandler).Methods("POST") http.Handle("/", r) log.Println("Listening on port 8080") c := cors.New(cors.Options{ AllowedOrigins: []string{"*"}, }) handler := c.Handler(r) log.Fatal(http.ListenAndServe(":8080", handler)) }
func Start(pipe *xeth.XEth, config RpcConfig) error { if rpclistener != nil { if fmt.Sprintf("%s:%d", config.ListenAddress, config.ListenPort) != rpclistener.Addr().String() { return fmt.Errorf("RPC service already running on %s ", rpclistener.Addr().String()) } return nil // RPC service already running on given host/port } l, err := newStoppableTCPListener(fmt.Sprintf("%s:%d", config.ListenAddress, config.ListenPort)) if err != nil { glog.V(logger.Error).Infof("Can't listen on %s:%d: %v", config.ListenAddress, config.ListenPort, err) return err } rpclistener = l var handler http.Handler if len(config.CorsDomain) > 0 { var opts cors.Options opts.AllowedMethods = []string{"POST"} opts.AllowedOrigins = []string{config.CorsDomain} c := cors.New(opts) handler = newStoppableHandler(c.Handler(JSONRPC(pipe)), l.stop) } else { handler = newStoppableHandler(JSONRPC(pipe), l.stop) } go http.Serve(l, handler) return nil }
// NewAPI instantiates a new API with a resolver. Sync determines whether to // sync the underlying repo with a remote origin func NewAPI(resolver Resolver) http.Handler { api := API{resolver: resolver} router := httprouter.New() router.GET("/", Index) router.POST("/token", api.tokenFn()) router.GET("/files/*path", api.wrap(GetFile)) router.DELETE("/files/*path", api.wrap(DeleteFile)) router.POST("/blobs", api.wrap(CreateBlob)) router.GET("/blobs/:sha", api.wrap(GetBlob)) router.POST("/trees", api.wrap(CreateTree)) router.GET("/trees/:sha", api.wrap(GetTree)) router.POST("/commits", api.wrap(CreateCommit)) router.GET("/commits/:sha", api.wrap(GetCommit)) router.GET("/refs/*ref", api.wrap(GetRef)) router.PATCH("/refs/*ref", api.wrap(UpdateRef)) corsHandler := cors.New(cors.Options{ AllowedMethods: []string{"GET", "POST", "PATCH", "PUT", "DELETE"}, AllowedHeaders: []string{"Accept", "Authorization", "Content-Type"}, AllowCredentials: true, }) return corsHandler.Handler(router) }
func main() { // middleware middle := interpose.New() middle.Use(adaptors.FromNegroni(cors.New(cors.Options{ // CORS AllowedOrigins: []string{"*"}, }))) // router router := pat.New() middle.UseHandler(router) router.Get("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { url := r.URL.Query().Get("url") if url != "" { encoded := imgbase64.FromRemote(url) fmt.Fprint(w, encoded) } else { fmt.Fprint(w, "/?url=<your-image-url> returns the base64 data-URI of that image.") } })) // listen port := os.Getenv("PORT") if port == "" { port = "5000" } log.Print("listening...") http.ListenAndServe(":"+port, middle) }
func main() { flag.Parse() if *helpFlag { fmt.Fprintf(os.Stderr, "Usage of %s\n", os.Args[0]) flag.PrintDefaults() os.Exit(1) } config := loadConfig(*configFile) logger := setupLogging(config.Log.File) mysqlDbmap := iamok.PrepareDBMap(config.MySql.ConnectionString) defer mysqlDbmap.Db.Close() mysqlDbmap.TraceOn("[gorp]", &Foo{}) router := iamok.NewRouter() //Logs the http requests status logHandler := handlers.LoggingHandler(logger, router) c := cors.New(cors.Options{ AllowedMethods: []string{"GET", "POST", "DELETE", "OPTIONS", "PUT"}, AllowedHeaders: []string{"X-Requested-With", "Accept", "Content-Type"}, Debug: true, }) //for accepting CORS requests http.ListenAndServe(":8080", iamok.RecoveryHandler{Handler: c.Handler(logHandler)}) }
// Route handler for the server func Handler() http.Handler { router := mux.NewRouter() // Set up the websocket server wsServer, err := socketio.NewServer(nil) if err != nil { log.Fatal(err) } wsServer.On("connection", func(so socketio.Socket) { log.Println("on connection") socket = so }) router.Handle("/socket.io/", wsServer) // GET /clients // List all registered registration IDs router.HandleFunc("/clients", ListClients).Methods("GET") // POST /message // Send a new message router.HandleFunc("/message", SendMessage).Methods("POST") c := cors.New(cors.Options{ AllowCredentials: true, }) return c.Handler(router) }
func main() { fmt.Println("Welcome to Sample bank Server:::::::") fmt.Println(time.Now()) ///DO db stuff appDb := AppDb{} appDb.initDb() appDb.initSchema() // appDb.createDummyData() c := cors.New(cors.Options{ AllowedOrigins: []string{"http://localhost:3500"}, }) // c := cors.Default() r := mux.NewRouter().StrictSlash(false) accounts := r.Path("/accounts").Subrouter() accounts.Methods("GET").HandlerFunc(appDb.accountsHandler) accounts.Methods("POST").HandlerFunc(appDb.createClientsHandler) account := r.PathPrefix("/accounts/{id}").Subrouter() account.Methods("GET").HandlerFunc(appDb.accountHandler) account.Methods("PUT").HandlerFunc(appDb.updateAccountHandler) account.Methods("DELETE").HandlerFunc(appDb.deleteHandler) http.ListenAndServe(":8050", c.Handler(r)) }
func (self *API) Serve() error { self.router = httprouter.New() if err := self.loadRoutes(); err != nil { return err } go func() { dc := diecast.NewServer() dc.Address = self.Address dc.Port = self.Port + 1 dc.LogLevel = `debug` if err := dc.Initialize(); err == nil { dc.Serve() } }() self.cors = cors.New(cors.Options{ AllowedOrigins: []string{`*`}, AllowedHeaders: []string{`*`}, }) self.server = negroni.New() self.server.Use(negroni.NewRecovery()) self.server.Use(self.cors) self.server.UseHandler(self.router) self.server.Run(fmt.Sprintf("%s:%d", self.Address, self.Port)) return nil }
func (s *Server) Start() error { n := negroni.New() n.Use(cors.New(cors.Options{ AllowCredentials: true, })) /* n.Use(&rest.CorsMiddleware{ RejectNonCorsRequests: false, OriginValidator: func(origin string, request *rest.Request) bool { return true }, AllowedMethods: []string{"GET", "POST"}, AllowedHeaders: []string{ "Accept", "Content-Type", "X-Custom-Header", "Origin"}, AccessControlAllowCredentials: true, AccessControlMaxAge: 3600, }) */ n.Use(negroni.NewRecovery()) n.Use(NewLogger()) n.UseFunc(s.Auth.LoginRequired) n.UseHandler(s.Api.Handler()) s.server = &graceful.Server{ Timeout: 10 * time.Second, Server: &http.Server{ Addr: s.Config.BindAddress, Handler: n, }, } s.listenAndGoServe() return nil }
func StartHttp(cfg HttpConfig, codec codec.Codec, api shared.EthereumApi) error { if httpListener != nil { if fmt.Sprintf("%s:%d", cfg.ListenAddress, cfg.ListenPort) != httpListener.Addr().String() { return fmt.Errorf("RPC service already running on %s ", httpListener.Addr().String()) } return nil // RPC service already running on given host/port } l, err := newStoppableTCPListener(fmt.Sprintf("%s:%d", cfg.ListenAddress, cfg.ListenPort)) if err != nil { glog.V(logger.Error).Infof("Can't listen on %s:%d: %v", cfg.ListenAddress, cfg.ListenPort, err) return err } httpListener = l var handler http.Handler if len(cfg.CorsDomain) > 0 { var opts cors.Options opts.AllowedMethods = []string{"POST"} opts.AllowedOrigins = strings.Split(cfg.CorsDomain, " ") c := cors.New(opts) handler = newStoppableHandler(c.Handler(gethHttpHandler(codec, api)), l.stop) } else { handler = newStoppableHandler(gethHttpHandler(codec, api), l.stop) } go http.Serve(l, handler) return nil }
// The main routine is going the "entry" point. func main() { // Create a new router. router := mux.NewRouter() // RESTful defines operations // * GET for fetching data // * POST for inserting data // * PUT for updating existing data // * DELETE for deleting data router.HandleFunc("/contacts", ListContacts(MyContacts)).Methods("GET") router.HandleFunc("/contacts/{id}", UpdateContact(MyContacts)).Methods("PUT") // The info endpoint is for showing demonstration purposes only and is not subject to any task. router.HandleFunc("/info", InfoHandler).Methods("GET") // Print where to point the browser at. fmt.Printf("Listening on %s\n", "http://localhost:5678") // Cross origin resource requests c := cors.New(cors.Options{ AllowedOrigins: []string{"*"}, AllowedMethods: []string{"GET", "POST", "DELETE", "PUT"}}, ) // Start up the server and check for errors. listenOn := fmt.Sprintf("%s:%s", envHost, envPort) err := http.ListenAndServe(listenOn, c.Handler(router)) if err != nil { log.Fatalf("Could not set up server because %s", err) } }
// RunServer starts vertice httpd server. func NewNegHandler() *negroni.Negroni { c := cors.New(cors.Options{ AllowedOrigins: []string{"*"}, }) m := &delayedRouter{} for _, handler := range megdHandlerList { m.Add(handler.method, handler.path, handler.h) } m.Add("Get", "/", Handler(index)) m.Add("Get", "/logs", Handler(logs)) m.Add("Get", "/ping", Handler(ping)) //we can use this as a single click Terminal launch for docker. //m.Add("Get", "/apps/{appname}/shell", websocket.Handler(remoteShellHandler)) n := negroni.New() n.Use(negroni.NewRecovery()) n.Use(c) n.Use(newLoggerMiddleware()) n.UseHandler(m) n.Use(negroni.HandlerFunc(contextClearerMiddleware)) n.Use(negroni.HandlerFunc(flushingWriterMiddleware)) n.Use(negroni.HandlerFunc(errorHandlingMiddleware)) n.Use(negroni.HandlerFunc(authTokenMiddleware)) n.UseHandler(http.HandlerFunc(runDelayedHandler)) return n }
func main() { log.SetFlags(log.LstdFlags | log.Lshortfile) flag.Parse() // Connect to RethinkDB var err error session, err = r.Connect(r.ConnectOpts{ Address: *rethinkAddress, }) if err != nil { log.Fatal(err) } // Create the database and tables r.DbCreate(*rethinkName).Exec(session) r.Db(*rethinkName).TableCreate("invites").Exec(session) r.Db(*rethinkName).Table("invites").IndexCreate("email").Exec(session) r.Db(*rethinkName).Table("invites").IndexCreate("name").Exec(session) // Add a CORS middleware goji.Use(cors.New(cors.Options{ AllowCredentials: true, }).Handler) // Add routes to goji goji.Get("/", index) goji.Post("/check", check) goji.Post("/free", free) goji.Post("/create", create) // Start the server goji.Serve() }
func Example() { session, err := mgo.Dial("") if err != nil { log.Fatalf("Can't connect to MongoDB: %s", err) } db := "test_rest_layer" index := resource.NewIndex() users := index.Bind("users", user, mongo.NewHandler(session, db, "users"), resource.Conf{ AllowedModes: resource.ReadWrite, }) users.Bind("posts", "user", post, mongo.NewHandler(session, db, "posts"), resource.Conf{ AllowedModes: resource.ReadWrite, }) api, err := rest.NewHandler(index) if err != nil { log.Fatalf("Invalid API configuration: %s", err) } http.Handle("/", cors.New(cors.Options{OptionsPassthrough: true}).Handler(api)) log.Print("Serving API on http://localhost:8080") if err := http.ListenAndServe(":8080", nil); err != nil { log.Fatal(err) } }
func main() { router := NewRouter() // connect mongoDB log.Println("Starting mongodb session") var err error session, err = mgo.Dial("localhost") if err != nil { panic(err) } defer session.Close() session.SetMode(mgo.Monotonic, true) // instantiate db & tokens collection as variable db = session.DB("confessions") tokens = session.DB("confessions").C("tokens") //cors c := cors.New(cors.Options{ AllowedOrigins: []string{"http://*****:*****@ localhost:8000") }
// StartHTTP starts listening for RPC requests sent via HTTP. func StartHttp(cfg HttpConfig, codec codec.Codec, api shared.EthereumApi) error { httpServerMu.Lock() defer httpServerMu.Unlock() addr := fmt.Sprintf("%s:%d", cfg.ListenAddress, cfg.ListenPort) if httpServer != nil { if addr != httpServer.Addr { return fmt.Errorf("RPC service already running on %s ", httpServer.Addr) } return nil // RPC service already running on given host/port } // Set up the request handler, wrapping it with CORS headers if configured. handler := http.Handler(&handler{codec, api}) if len(cfg.CorsDomain) > 0 { opts := cors.Options{ AllowedMethods: []string{"POST"}, AllowedOrigins: strings.Split(cfg.CorsDomain, " "), } handler = cors.New(opts).Handler(handler) } // Start the server. s, err := listenHTTP(addr, handler) if err != nil { glog.V(logger.Error).Infof("Can't listen on %s:%d: %v", cfg.ListenAddress, cfg.ListenPort, err) return err } httpServer = s return nil }
func setupMiddleware() []http.Handler { return []http.Handler{ adaptors.HandlerFromNegroni(cors.New(cors.Options{ AllowedOrigins: viper.GetStringSlice("cors.allowed_origins"), AllowedMethods: viper.GetStringSlice("cors.allowed_methods"), AllowCredentials: viper.GetBool("cors.allow_credentials"), })), adaptors.HandlerFromNegroni(negroni.HandlerFunc(secure.New(secure.Options{ AllowedHosts: []string{}, SSLRedirect: false, SSLTemporaryRedirect: false, SSLHost: "", SSLProxyHeaders: map[string]string{}, STSSeconds: 0, STSIncludeSubdomains: false, STSPreload: false, ForceSTSHeader: false, FrameDeny: false, CustomFrameOptionsValue: "", ContentTypeNosniff: false, BrowserXssFilter: false, ContentSecurityPolicy: "", IsDevelopment: viper.GetString("environment") == "development", }).HandlerFuncWithNext)), } }
// setup prepares the internal HTTP handle, middleware, and resources. func (s *Server) setup() { e := echo.New() s.core = e // Enable HTTP 2 e.HTTP2(true) // Toggle debug e.SetDebug(s.Debug) // Setup middleware. e.Use(mw.Logger()) e.Use(mw.Recover()) e.Use(mw.Gzip()) // Setup CORS. e.Use(cors.New(cors.Options{ AllowedOrigins: s.AllowedHosts, }).Handler) // Add middleware for setting the server context. e.Use(s.serverContext) e.Get("/", httpRoot) e.Get("/domains", httpDomains) e.Get("/log/:domain", httpLog) e.Get("/log/:domain/entities", httpDomainEntities) e.Get("/log/:domain/attributes", httpDomainAttributes) e.Get("/log/:domain/values", httpDomainValues) e.Get("/timeline/:domain", httpTimeline) }
func main() { helpers.InitLogger() config.SetupConstants() if config.Constants.ProfilerEnable { address := "localhost:" + config.Constants.ProfilerPort go func() { graceful.Run(address, 1*time.Second, nil) }() helpers.Logger.Debug("Running Profiler at %s", address) } pid := &pid.Instance{} if pid.Create() == nil { defer pid.Remove() } authority.RegisterTypes() helpers.InitAuthorization() database.Init() migrations.Do() stores.SetupStores() models.PaulingConnect() models.FumbleConnect() models.InitializeLobbySettings("./lobbySettingsData.json") StartPaulingListener() chelpers.InitDB() if config.Constants.SteamIDWhitelist != "" { go chelpers.WhitelistListener() } // lobby := models.NewLobby("cp_badlands", 10, "a", "a", 1) helpers.Logger.Debug("Starting the server") // init http server // init socket.io server server := wsevent.NewServer() nologin := wsevent.NewServer() broadcaster.Init(server, nologin) socket.ServerInit(server, nologin) routes.SetupHTTPRoutes(server, nologin) if val := os.Getenv("DEPLOYMENT_ENV"); strings.ToLower(val) != "production" { // init static FileServer // TODO be careful to set this to correct location when deploying http.HandleFunc("/static/", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, r.URL.Path[1:]) }) } corsHandler := cors.New(cors.Options{ AllowedOrigins: config.Constants.AllowedCorsOrigins, AllowCredentials: true, }).Handler(http.DefaultServeMux) // start the server helpers.Logger.Debug("Serving at %s", config.Constants.Domain) graceful.Run(":"+config.Constants.Port, 1*time.Second, corsHandler) }
func main() { //setup sessions /* sh := redis.NewSessionHolder() redisconfig := viper.GetStringMapString("redis") if _, ok := redisconfig["host"]; !ok { panic("failed to read redis host") } if _, ok := redisconfig["port"]; !ok { panic("failed to read redis port") } redisip, err := alias2ipaddr(redisconfig["host"]) if err != nil { panic("failed to lookup redis IP address") } goji.Use(redis.BuildRedis(fmt.Sprintf("%s:%s", redisip, redisconfig["port"]))) goji.Use(base.BuildSessionMiddleware(sh)) */ c := cors.New(cors.Options{ AllowedOrigins: []string{"*"}, }) goji.Use(c.Handler) //setup render middleware goji.Use(middleware.RenderMiddleware) //setup database /* dbconfig := viper.GetStringMapString("db") if _, ok := dbconfig["host"]; !ok { panic("failed to read db host") } if _, ok := dbconfig["name"]; !ok { panic("failed to read db name") } goji.Use(middleware.PostgresMiddleware) goji.Use(middleware.AuthMiddleware) */ //setup routes goji.Get("/home", controllers.IndexHandler) goji.Get("/healthcheck", controllers.HealthCheckHandler) goji.Get("/login", controllers.Login) goji.Get("/oauth2callback", controllers.OAuth2Callback) //goji.Get("/logout", controllers.Logout) //setup static assets goji.Use(gojistatic.Static("/go/src/bower_components", gojistatic.StaticOptions{SkipLogging: true, Prefix: "bower_components"})) goji.Use(gojistatic.Static("/go/src/frontend/js", gojistatic.StaticOptions{SkipLogging: true, Prefix: "js"})) //begin log.Info("Starting App...") flag.Set("bind", ":80") goji.Serve() }
func main() { // Create a REST API resource index index := resource.NewIndex() // Add a resource on /users[/:user_id] users := index.Bind("users", user, mem.NewHandler(), resource.Conf{ // We allow all REST methods // (rest.ReadWrite is a shortcut for []resource.Mode{resource.Create, resource.Read, resource.Update, resource.Delete, resource,List}) AllowedModes: resource.ReadWrite, }) // Bind a sub resource on /users/:user_id/posts[/:post_id] // and reference the user on each post using the "user" field of the posts resource. posts := users.Bind("posts", "user", post, mem.NewHandler(), resource.Conf{ // Posts can only be read, created and deleted, not updated AllowedModes: []resource.Mode{resource.Read, resource.List, resource.Create, resource.Delete}, }) // Add a friendly alias to public posts // (equivalent to /users/:user_id/posts?filter={"published":true}) posts.Alias("public", url.Values{"filter": []string{"{\"published\":true}"}}) // Create API HTTP handler for the resource graph api, err := rest.NewHandler(index) if err != nil { log.Fatalf("Invalid API configuration: %s", err) } c := alice.New() // Add close notifier handler so context is cancelled when the client closes // the connection // c.Append(xhandler.CloseHandler) // Add timeout handler // c.Append(xhandler.TimeoutHandler(2 * time.Second)) // Install a logger (see https://github.com/rs/xlog) c = c.Append(xlog.NewHandler(xlog.Config{})) resource.LoggerLevel = resource.LogLevelDebug resource.Logger = func(ctx context.Context, level resource.LogLevel, msg string, fields map[string]interface{}) { xlog.FromContext(ctx).OutputF(xlog.Level(level), 2, msg, fields) } // Log API access c = c.Append(xaccess.NewHandler()) // Add CORS support with passthrough option on so rest-layer can still // handle OPTIONS method c = c.Append(cors.New(cors.Options{OptionsPassthrough: true}).Handler) // Bind the API under /api/ path http.Handle("/api/", http.StripPrefix("/api/", c.Then(api))) // Serve it log.Print("Serving API on http://localhost:8080") if err := http.ListenAndServe(":8080", nil); err != nil { log.Fatal(err) } }
func (s *Server) corsHandler(h http.Handler) http.Handler { dirs := s.conf.GetDirectives() opts := cors.Options{} opts.AllowedOrigins = dirs.Server.CORSAccessControlAllowOrigin opts.AllowedMethods = dirs.Server.CORSAccessControlAllowMethods opts.AllowedHeaders = dirs.Server.CORSAccessControlAllowHeaders return cors.New(opts).Handler(h) }
// CorsHandler handler for CORS (Cross Origin Resource Sharing) func CorsHandler(h http.Handler) http.Handler { c := cors.New(cors.Options{ AllowedOrigins: []string{"*"}, AllowedMethods: []string{"GET", "HEAD", "POST", "PUT"}, AllowedHeaders: []string{"*"}, }) return c.Handler(h) }
func buildCORS(debug bool) *cors.Cors { return cors.New(cors.Options{ AllowedOrigins: []string{"http://localhost*"}, AllowedHeaders: []string{"*"}, AllowedMethods: []string{"POST", "PATCH", "GET", "DELETE"}, Debug: debug, }) }
func CORSHandler() web.MiddlewareType { var c *cors.Cors c = cors.New(cors.Options{ AllowedOrigins: []string{"*"}, AllowedMethods: []string{"GET", "POST", "OPTIONS"}, AllowCredentials: true, }) return c.Handler }
func Init(e *echo.Echo, Debug bool) { c := cors.New(cors.Options{ AllowedOrigins: []string{"*"}, AllowedMethods: []string{"GET", "POST", "DELETE", "PUT", "PATCH"}, AllowCredentials: true, Debug: Debug, }) e.Use(standard.WrapMiddleware(c.Handler)) }
func RegisterRoutes(r *mux.Router, cfg config.Config) { routes := gen.BuildRoutes() jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{ ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) { return []byte(cfg.Secret), nil }, // When set, the middleware verifies that tokens are signed with the specific signing algorithm // If the signing method is not constant the ValidationKeyGetter callback can be used to implement additional checks // Important to avoid security issues described here: https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/ SigningMethod: jwt.SigningMethodHS256, }) corsMlw := cors.New(cors.Options{ AllowedOrigins: cfg.CORSAllowedOrigins, AllowedMethods: cfg.CORSAllowedMethods, AllowedHeaders: cfg.CORSAllowedHeaders, ExposedHeaders: cfg.CORSExposedHeaders, AllowCredentials: cfg.CORSAllowCredentials, MaxAge: cfg.CORSMaxAge, OptionsPassthrough: cfg.CORSOptionsPassThrough, Debug: cfg.CORSDebug, }) for _, rt := range routes { apiRouter := mux.NewRouter().StrictSlash(true) for _, route := range rt.Routes { handlerFunc := negroni.New() // Add CORS middleware handlerFunc.Use(corsMlw) // Add JWT middleware if route is protected if route.Protected { handlerFunc.Use(negroni.HandlerFunc(jwtMiddleware.HandlerWithNext)) } apiRouter. Methods(route.Method...). Name(route.Name). Path(fmt.Sprintf("%s%s", rt.BasePattern, route.Pattern)). Queries(route.Queries...). HandlerFunc(route.HandlerFunc) // Add actual handler handlerFunc.Use(negroni.Wrap(apiRouter)) r.PathPrefix(rt.BasePattern).Handler(handlerFunc) ctxLog.WithField("base-path", rt.BasePattern). WithField("protected", route.Protected). WithField("name", route.Name). WithField("path", fmt.Sprintf("%s%s", rt.BasePattern, route.Pattern)). WithField("method", route.Method). WithField("query", fmt.Sprintf("%+v", route.Queries)). Debugf("%+v", route) } } }
func CORS(c *web.C, h http.Handler) http.Handler { cors := cors.New(cors.Options{ AllowedOrigins: []string{"*"}, AllowedHeaders: []string{"*"}, AllowedMethods: []string{"GET", "POST", "PATCH"}, Debug: true, }) return cors.Handler(h) }
func main() { // Initialize routes r := router.Init(nerdz.Configuration.EnableLog) // Enalble CORS globally r.Use(echo.WrapMiddleware(cors.New(cors.Options{}).Handler)) // Recover from panics r.Use(middleware.Recover()) // Start the router r.Start(":" + strconv.Itoa(int(nerdz.Configuration.Port))) }