当前位置: 首页>>代码示例>>Golang>>正文


Golang cors.Default函数代码示例

本文整理汇总了Golang中github.com/rs/cors.Default函数的典型用法代码示例。如果您正苦于以下问题:Golang Default函数的具体用法?Golang Default怎么用?Golang Default使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Default函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: RunServer

func RunServer(c *cli.Context) error {

	// logging middleware
	loggerMw, err := getLoggerMiddleware(c)
	if err != nil {
		return cli.NewExitError(err.Error(), 2)
	}
	// middleware chain
	baseChain := chain.NewChain(loggerMw.MiddlewareFn, cmw.CorsAdapter(cors.Default()))

	// database handler
	dbh, err := getPgWrapper(c)
	if err != nil {
		return cli.NewExitError(err.Error(), 2)
	}
	// http routes
	r := router.NewRouter()
	routes.AddPublication(&publication.Publication{dbh, c.String("version")}, baseChain, r)
	routes.AddAuthor(&publication.Author{dbh, c.String("version")}, baseChain, r)

	// start the server
	log.Printf("Starting modware api web server on port %d\n", c.Int("port"))
	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", c.Int("port")), r.Router))
	return nil
}
开发者ID:dictyBase,项目名称:Modware,代码行数:25,代码来源:server.go

示例2: ExampleAddChain

func ExampleAddChain() {
	c := xhandler.Chain{}

	close := xhandler.CloseHandler
	cors := cors.Default().Handler
	timeout := xhandler.TimeoutHandler(2 * time.Second)
	auth := func(next xhandler.HandlerC) xhandler.HandlerC {
		return xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			if v := ctx.Value("Authorization"); v == nil {
				http.Error(w, "Not authorized", http.StatusUnauthorized)
				return
			}
			next.ServeHTTPC(ctx, w, r)
		})
	}

	c.Add(close, cors, timeout)

	mux := http.NewServeMux()

	// Use c.Handler to terminate the chain with your final handler
	mux.Handle("/", c.Handler(xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Welcome to the home page!")
	})))

	// Create a new chain from an existing one, and add route-specific middleware to it
	protected := c.With(auth)

	mux.Handle("/admin", protected.Handler(xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "protected endpoint!")
	})))
}
开发者ID:stellar,项目名称:bridge-server,代码行数:32,代码来源:chain_example_test.go

示例3: main

// TODO : need to change to init ,this server it should run by core main.
func main() {
	fmt.Println("api server is started ... ", "\n", "port :8182 :443")
	router := NewRouter()
	handler := cors.Default().Handler(router)
	log.Fatal(http.ListenAndServeTLS(":443", "/root/.lego/certificates/paas.jigko.net.crt", "/root/.lego/certificates/paas.jigko.net.key", handler))
	///root/.lego/certificates/paas.jigko.net.crt
}
开发者ID:SOUP-CE-KMITL,项目名称:Thoth,代码行数:8,代码来源:main.go

示例4: corsHandler

func corsHandler() gin.HandlerFunc {
	handler := cors.Default()
	return func(c *gin.Context) {
		handler.HandlerFunc(c.Writer, c.Request)
		c.Next()
	}
}
开发者ID:dcu,项目名称:git-http-server,代码行数:7,代码来源:git-http-server.go

示例5: main

func main() {
	//TODO user httproute package
	r := httprouter.New()

	r.GET("/ws/:roomHash/connect/:userHash", model.ConnectToRoom)

	r.GET("/", serveHome)

	r.POST("/users/create", model.UserCreate)

	r.POST("/rooms/create", model.CreateRoom)

	r.GET("/rooms/get", model.GetRooms)
	r.GET("/rooms/users/:roomHash", model.GetRoomUsers)

	r.ServeFiles("/static/*filepath", http.Dir("./static/"))

	flag.Parse()

	handler := cors.Default().Handler(r)

	log.Println("Server running on port: 8000")
	err := http.ListenAndServe(":8000", handler)

	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
开发者ID:valiknet18,项目名称:WebSocketChat,代码行数:28,代码来源:main.go

示例6: main

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	fetchFeed()

	e := echo.New()
	e.Use(mw.Logger())
	e.Use(mw.Recover())
	e.Use(mw.StripTrailingSlash())
	e.Use(mw.Gzip())
	e.Use(cors.Default().Handler)

	bundle, _ := ioutil.ReadFile("./build/bundle.js")

	// stats
	s := stats.New()
	e.Use(s.Handler)
	e.Get("/stats", func(c *echo.Context) error {
		return c.JSON(http.StatusOK, s.Data())
	})
	// static files
	e.Static("/public/css", "public/css")
	e.Static("/universal.js", "./build/bundle.js")
	e.Favicon("public/favicon.ico")

	e.Get("/", selfjs.New(runtime.NumCPU(), string(bundle), rss))
	e.Get("/about", selfjs.New(runtime.NumCPU(), string(bundle), loremJSON()))

	e.Get("/api/data", apiFrontPage)
	e.Get("/api/anotherpage", apiAnotherPage)
	go tick()
	fmt.Println("serving at port 3000")
	e.Run(":3000")
}
开发者ID:jelinden,项目名称:go-isomorphic-react-v8,代码行数:33,代码来源:main.go

示例7: BuildHandler

func BuildHandler(utilsFunc utils.UtilsFunc, doGzip bool) http.Handler {
	uf = utilsFunc
	mux := http.NewServeMux()

	fs := http.FileServer(httpFs{http.Dir("public")})
	mux.Handle("/css/", fs)
	mux.Handle("/html/", fs)
	mux.Handle("/img/", fs)

	mux.HandleFunc("/", httpRedirect)
	mux.HandleFunc("/js/all.js", httpAllJs)
	mux.HandleFunc("/js/data.json", httpDataJson)
	mux.HandleFunc("/js/jquery.plugin.js", httpJqueryPluginJs)
	mux.HandleFunc("/v2/js/data.json", httpDataJson2)
	mux.HandleFunc("/v2/js/history.json", httpHistoryJson)

	mux.HandleFunc("/config", httpConfig)

	handler := cors.Default().Handler(mux)
	if !doGzip {
		return handler
	}

	return gziphandler.GzipHandler(handler)
}
开发者ID:daohoangson,项目名称:go-socialcounters,代码行数:25,代码来源:init.go

示例8: main

func main() {
	if len(os.Args) != 3 {
		fmt.Fprintf(os.Stderr, "%s <comments-path> <addr>\n", os.Args[0])
		os.Exit(2)
	}
	path = os.Args[1]
	if strings.HasSuffix(path, "/") {
		path = path[:len(path)-1]
	}
	addr = os.Args[2]
	fmt.Println("looking for comments in", path)
	fmt.Println("will listen for http traffic on", addr)

	http.Handle("/", cors.Default().Handler(
		http.HandlerFunc(
			func(w http.ResponseWriter, r *http.Request) {
				if r.Method == "POST" {
					handlePost(w, r)
				} else {
					handleGet(w, r)
				}
			},
		),
	),
	)
	http.ListenAndServe(addr, nil)
}
开发者ID:Dieterbe,项目名称:comma,代码行数:27,代码来源:main.go

示例9: main

func main() {
	if len(os.Args) != 3 {
		fmt.Fprintf(os.Stderr, "%s <csv-file> <addr>\n", os.Args[0])
		os.Exit(2)
	}

	csvPath = os.Args[1]
	addr = os.Args[2]

	setupCsv(Subscriber{})

	fmt.Println("CSV file located at", csvPath)
	fmt.Println("listening on", addr)

	http.Handle("/subscribe", cors.Default().Handler(
		http.HandlerFunc(
			func(w http.ResponseWriter, r *http.Request) {
				if r.Method == "POST" {
					handlePost(w, r)
				} else {
					http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
				}
			},
		),
	))
	http.ListenAndServe(addr, nil)
}
开发者ID:alextyrey,项目名称:lander,代码行数:27,代码来源:main.go

示例10: StartServer

func StartServer(portNumber int) (err error) {

	mux := http.NewServeMux()

	// Root: Show status of service
	mux.HandleFunc("/", StatusHandler)

	// Convert CX stream into Cytoscape JS
	mux.HandleFunc("/cx2cyjs", Cx2CyjsHandler)

	// Utility to convert network stored in NDEx into Cytoscape.js
	mux.HandleFunc("/ndex2cyjs/", Ndex2CyjsHandler)

	handler := cors.Default().Handler(mux)

	log.Println("Serving cxtool API on port ", portNumber)

	portNumStr := strconv.Itoa(portNumber)

	err = http.ListenAndServe(":"+portNumStr, handler)

	if err != nil {
		log.Fatal("Could not start API server: ", err)
	}

	return nil
}
开发者ID:CyService,项目名称:service-cxtool,代码行数:27,代码来源:routing.go

示例11: main

/**
 * Main entry point for the web service
 */
func main() {
	lf, _ := os.OpenFile("service.log", os.O_APPEND|os.O_CREATE|os.O_RDWR, 0777)
	defer lf.Close()
	logger = log.New(lf, "service: ", log.LstdFlags)
	// use below to log to console....
	//logger = log.New(os.Stdout, "logger: ", log.LstdFlags)

	// Load cfg
	logger.Printf("===> pdf-ws staring up <===")
	logger.Printf("Load configuration...")
	viper.SetConfigName("config")
	viper.SetConfigType("yml")
	viper.AddConfigPath(".")
	err := viper.ReadInConfig()
	if err != nil {
		fmt.Printf("Unable to read config: %s", err.Error())
		os.Exit(1)
	}

	// Init DB connection
	logger.Printf("Init DB connection...")
	connectStr := fmt.Sprintf("%s:%[email protected](%s)/%s?allowOldPasswords=%s", viper.GetString("db_user"), viper.GetString("db_pass"),
		viper.GetString("db_host"), viper.GetString("db_name"), viper.GetString("db_old_passwords"))
	db, err = sql.Open("mysql", connectStr)
	if err != nil {
		fmt.Printf("Database connection failed: %s", err.Error())
		os.Exit(1)
	}
	defer db.Close()

	// Set routes and start server
	mux := httprouter.New()
	mux.GET("/", rootHandler)
	mux.GET("/:pid", pdfGenerate)
	mux.GET("/:pid/status", statusHandler)
	mux.GET("/:pid/download", downloadHandler)
	logger.Printf("Start service on port %s", viper.GetString("port"))

	if viper.GetBool("https") == true {
		crt := viper.GetString("ssl_crt")
		key := viper.GetString("ssl_key")
		log.Fatal(http.ListenAndServeTLS(":"+viper.GetString("port"), crt, key, cors.Default().Handler(mux)))
	} else {
		log.Fatal(http.ListenAndServe(":"+viper.GetString("port"), cors.Default().Handler(mux)))
	}
}
开发者ID:uvalib,项目名称:pdf-ws,代码行数:49,代码来源:pdf-ws.go

示例12: init

func init() {
	router := httprouter.New()

	router.OPTIONS("/", api.Options)
	router.GET("/", api.UserInterface)
	router.POST("/bench", api.Boomer)

	http.Handle("/", cors.Default().Handler(router))
}
开发者ID:ninnemana,项目名称:boomer,代码行数:9,代码来源:init.go

示例13: main

func main() {
	fromEmail = os.Getenv("FROMEMAIL")
	emailSendingPasswd = os.Getenv("EMAILSENDINGPASSWD")
	if fromEmail == "" || emailSendingPasswd == "" {
		log.Fatal("FROMEMAIL or EMAILSENDINGPASSWD was not set")
	}
	runtime.GOMAXPROCS(runtime.NumCPU())
	app := NewApplication()
	app.Init()
	e := echo.New()

	e.Use(middleware.HttpLogger())
	e.HTTP2()
	e.SetHTTPErrorHandler(app.errorHandler)
	e.Use(mw.Recover())
	e.Use(mw.Gzip())
	e.StripTrailingSlash()
	e.Use(cors.Default().Handler)
	/* TODO: logs too much
	newrelickey, found := os.LookupEnv("NEWRELICKEY")
	if found == true {
		gorelic.InitNewRelicAgent(newrelickey, "go-register-login", true)
		e.Use(gorelic.Handler())
	}
	*/
	s := stats.New()
	e.Use(s.Handler)

	e.Get("/stats", func(c *echo.Context) error {
		return c.JSON(http.StatusOK, s.Data())
	})

	e.Favicon("public/favicon.ico")
	e.Static("/public/css", "public/css")
	e.Static("/universal.js", "./build/bundle.js")

	bundle, _ := ioutil.ReadFile("./build/bundle.js")
	user, _ := json.Marshal(domain.User{})

	e.Get("/", selfjs.New(runtime.NumCPU(), string(bundle), string(user)))
	e.Get("/register", selfjs.New(runtime.NumCPU(), string(bundle), string(user)))
	e.Get("/login", selfjs.New(runtime.NumCPU(), string(bundle), string(user)))

	admin := e.Group("/members")
	admin.Use(middleware.CheckAdmin(app.Redis, string(bundle)))
	admin.Get("", selfjs.New(runtime.NumCPU(), string(bundle), app.listUsers()))

	e.Get("/api/users", app.listUsersAPI)
	e.Get("/api/user/:id", app.userAPI)
	e.Get("/verify/:id/:hash", app.verifyEmail)
	e.Post("/register", app.createUser)
	e.Get("/logout", app.logout)
	e.Post("/login", app.login)
	fmt.Println("Starting server at port 3300")
	e.Run(":3300")
}
开发者ID:JC1738,项目名称:go-react-seed,代码行数:56,代码来源:server.go

示例14: main

func main() {
	h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte("{\"hello\": \"world\"}"))
	})

	// Use default options
	handler := cors.Default().Handler(h)
	http.ListenAndServe(":8080", handler)
}
开发者ID:CedarLogic,项目名称:go-ethereum,代码行数:10,代码来源:server.go

示例15: main

func main() {
	r := httprouter.New()
	r.GET("/r/:id", DispatchHandler)
	r.POST("/api/short", CreateShortedURLHandler)
	r.GET("/api/stats/:id", ViewStatisticsHandler)
	r.GET("/api/stats", ListURLHandler)

	handler := cors.Default().Handler(r)
	logging("Starting server %d...", *port)
	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), handler))
}
开发者ID:yuriadams,项目名称:shorter,代码行数:11,代码来源:server.go


注:本文中的github.com/rs/cors.Default函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。