• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang cors.Default函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: StartHttpServerBlocking

// StartHttpServerBlocking is a blocking method which takes an arbritrary number
// of HttpServeables, adds all their routes the http mux and starts a server on
// the configured port and address.
func StartHttpServerBlocking(serveables ...HttpServeable) {
	router := AssembleRouter(serveables...)
	httpPort := conf.Global.UInt("http.port", 8080)
	httpAddress := conf.Global.UString("http.address", "")
	httpListenAddr := fmt.Sprintf("%s:%d", httpAddress, httpPort)
	log.Printf("Trying to http listen on %s", httpListenAddr)
	handler := cors.Default().Handler(router)
	http.Handle("/", handler)
	http.Handle("/metrics", stat.Handler())
	log.Fatal(http.ListenAndServe(httpListenAddr, nil))
}
开发者ID:tantive,项目名称:node-informant,代码行数:14,代码来源:server.go


示例17: main

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", handler)
	mux.HandleFunc("/submit/", submitHandler)

	// cors.Default() setup the middleware with default options being
	// all origins accepted with simple methods (GET, POST). See
	// documentation below for more options.
	handler := cors.Default().Handler(mux)
	http.ListenAndServe("localhost:8081", handler)
}
开发者ID:garoevans,项目名称:data-provider-service-go,代码行数:11,代码来源:main.go


示例18: main

func main() {
	log.Println("VERSION: ", VERSION)
	e := echo.New()
	e.Use(middleware.Logger())
	e.Use(middleware.Recover())
	e.Use(cors.Default().Handler)
	e.Index("public/index.html")
	e.Static("/", "public")

	if len(os.Args) < 2 {
		fmt.Println("\nPlease input callback url.\n  Usage: app.exe [callback_url]")
		os.Exit(0)
	}
	callback_url = os.Args[1]
	//e.Favicon("public/favicon.ico")

	server, err := socketio.NewServer(nil)
	if err != nil {
		log.Fatal(err)
	}
	e.Get("/publish/photo", CallbackHandler)
	e.Post("/publish/photo", ReceiveHandler)
	e.Get("/socket.io/", server)

	server.On("connection", func(so socketio.Socket) {
		log.Println("====================== on connection ======================")
		result := make([]interface{}, 12)
		cur, err := r.Table("instacat").OrderBy(r.OrderByOpts{
			Index: r.Desc("time"),
		}).Limit(12).Run(session)
		if err != nil {
			log.Println(err.Error())
		}
		cur.All(&result)
		fmt.Println("Get result over. ")
		err = so.Emit("recent", result)
		if err != nil {
			log.Println(err.Error())
		}
		so.On("disconnect", func() {
			log.Println("on disconnect")
		})

		RealtimeChangefeed(so)
	})

	//go SubscribeTag()
	go sub()
	port := ":3000"
	log.Printf("Starting HTTP service on %s ...", port)
	e.Run(port)

}
开发者ID:jimmyplaza,项目名称:RethinkDB-Instagram,代码行数:53,代码来源:main.go


示例19: main

func main() {
	index := resource.NewIndex()

	// configure your resources

	api, err := rest.NewHandler(index)
	if err != nil {
		log.Fatalf("Invalid API configuration: %s", err)
	}

	handler := cors.Default().Handler(api)
	log.Fatal(http.ListenAndServe(":8080", handler))
}
开发者ID:rs,项目名称:rest-layer,代码行数:13,代码来源:main.go


示例20: main

func main() {

	mx := mux.NewRouter()
	mx.HandleFunc("/{js_filename}.js", ServeJS)
	mx.HandleFunc("/getfiles/callback={callback}", GetFiles)
	mx.HandleFunc("/index", Index)
	mx.HandleFunc("/upload", Upload)

	n := negroni.Classic()
	n.UseHandler(cors.Default().Handler(mx))

	n.Run(":" + os.Getenv("PORT"))
}
开发者ID:willnix,项目名称:webchan,代码行数:13,代码来源:websrv.go



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang cors.New函数代码示例发布时间:2022-05-28
下一篇:
Golang neat.Context类代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap