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

Golang cors.Allow函数代码示例

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

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



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

示例1: Run

func (this *Server) Run(withRandomPort ...bool) {
	this.Martini.Use(cors.Allow(&cors.Options{
		AllowAllOrigins:  true,
		AllowMethods:     []string{"PUT", "PATCH", "DELETE", "GET", "OPTIONS", "POST"},
		AllowCredentials: true,
	}))
	this.Martini.Use(render.Renderer())

	this.Martini.Group("/eureka", func(r martini.Router) {
		for _, request := range this.getRequestsEureka() {
			request.SetRoutes(r)
		}
	})
	this.registerJobsRoutes()
	if len(withRandomPort) > 0 && withRandomPort[0] {
		listener, err := net.Listen("tcp", "127.0.0.1:0")
		if err != nil {
			loggerServer.Severe("Error when getting a free random port: %v", err.Error())
		}
		host := listener.Addr().String()
		listener.Close()
		this.Martini.RunOnAddr(host)
	} else if config.GetConfig().Host != "" {
		this.Martini.RunOnAddr(config.GetConfig().Host)
	} else {
		this.Martini.Run()
	}

}
开发者ID:ArthurHlt,项目名称:microcos,代码行数:29,代码来源:server.go


示例2: main

func main() {
	api := &api.API{
		ApiKey: "122cc483be92bd806b696e7d458596ac",
		DataCacheRenewalInterval: 15,
	}
	api.Setup()
	go api.CyclicCacheRenewal()

	m := martini.Classic()
	m.Map(api)

	m.Use(cors.Allow(&cors.Options{
		AllowAllOrigins:  true,
		AllowCredentials: true,
	}))

	m.Use(func(c martini.Context, w http.ResponseWriter) {
		c.MapTo(encoder.JsonEncoder{}, (*encoder.Encoder)(nil))
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
	})

	m.Get("/photos/:name", func(params martini.Params,
		enc encoder.Encoder) (int, []byte) {
		name, ok := params["name"]

		if ok {
			photos, _ := api.GetPhotosForUser(name)
			return http.StatusOK, encoder.Must(enc.Encode(photos))
		}

		return 404, []byte("Not Found")
	})
	m.Run()
}
开发者ID:pboehm,项目名称:flickrit,代码行数:34,代码来源:flickrit.go


示例3: listen

func (r *RestServer) listen() error {

	m := martini.Classic()

	m.Use(cors.Allow(&cors.Options{
		AllowAllOrigins: true,
	}))

	// m.Map(r.TaskModel)

	task := NewTaskRouter()
	task.scheduler = r.Scheduler

	m.Group("/rest/v1/tasks", task.Register)

	listenAddress := fmt.Sprintf(":%d", config.MustInt("app-scheduler.rest.port"))

	r.log.Infof("Listening at %s", listenAddress)

	srv := &http.Server{Addr: listenAddress, Handler: m}
	ln, err := net.Listen("tcp", listenAddress)
	if err != nil {
		return err
	}

	return srv.Serve(listener{
		TCPListener: ln.(*net.TCPListener),
		stop:        make(chan struct{}),
	})
}
开发者ID:froz,项目名称:app-scheduler,代码行数:30,代码来源:RestServer.go


示例4: Start

func (h *HTTPService) Start() {
	fmt.Println("Object Store Listening on Port : 3000")
	m := martini.Classic()
	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE"},
		AllowHeaders:     []string{"securityToken", "Content-Type"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))
	//READ BY KEY
	m.Get("/:namespace/:class/:id", handleRequest)
	//READ BY KEYWORD
	m.Get("/:namespace/:class", handleRequest)
	//Get all classes
	m.Post("/:namespace", handleRequest)
	//READ ADVANCED, INSERT
	m.Post("/:namespace/:class", handleRequest)

	//FILE RECIEVER
	m.Post("/:namespace/:class/:id", uploadHandler)
	//UPDATE
	m.Put("/:namespace/:class", handleRequest)
	//DELETE
	m.Delete("/:namespace/:class", handleRequest)

	m.Run()
}
开发者ID:sajeetharan,项目名称:v6engine,代码行数:28,代码来源:HTTPService.go


示例5: main

/*
Application entry point
*/
func main() {
	m := martini.New()

	//Set middleware
	m.Use(martini.Recovery())
	m.Use(martini.Logger())

	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"OPTIONS", "HEAD", "POST", "GET", "PUT"},
		AllowHeaders:     []string{"Authorization", "Content-Type"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))

	//Create the router
	r := martini.NewRouter()

	//Options matches all and sends okay
	r.Options(".*", func() (int, string) {
		return 200, "ok"
	})

	api.SetupTodoRoutes(r)
	api.SetupCommentRoutes(r)

	mscore.StartServer(m, r)
	fmt.Println("Started NSQ Test service")
}
开发者ID:newsquid,项目名称:newsquidtest,代码行数:32,代码来源:main.go


示例6: ListenAndServe

// ListenAndServe start the server
func ListenAndServe(addr string, core core.Core, fe fs.FileExplorer) {
	log.Infof("REST listening at: http://%v", core.GetAddr())
	clientHandlers := clientAPI.NewHandler(core)
	mesosHandlers := mesosAPI.NewHandler(core)
	fsHandlers := fsAPI.NewHandler(fe)
	r := createRouter(core, clientHandlers, mesosHandlers, fsHandlers)

	m := martini.New()
	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"POST", "GET", "PUT", "DELETE"},
		AllowHeaders:     []string{"Origin", "x-requested-with", "Content-Type", "Content-Range", "Content-Disposition", "Content-Description"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: false,
	}))
	m.Use(logger())
	m.Use(recovery())
	m.Use(martini.Static("static"))
	m.Use(martini.Static("temp", martini.StaticOptions{
		Prefix: "/context/",
	}))
	m.Use(martini.Static("executor", martini.StaticOptions{
		Prefix: "/executor/",
	}))
	m.Action(r.Handle)
	go m.RunOnAddr(addr)
}
开发者ID:icsnju,项目名称:apt-mesos,代码行数:28,代码来源:server.go


示例7: App

func App() *martini.ClassicMartini {
	m := martini.Classic()

	m.Use(gzip.All())

	m.Use(render.Renderer(render.Options{
		Directory: "templates",
	}))

	m.Use(cors.Allow(&cors.Options{
		AllowAllOrigins: true,
	}))

	m.Get("", Index)

	m.Group("/repos", func(r martini.Router) {
		r.Get("", ReposIndex)
		r.Get("/:name", ReposShow)
	})

	m.Group("/orgs", func(r martini.Router) {
		r.Get("", OrgsIndex)
		r.Get("/:id", OrgsShow)
	})

	m.Group("/users", func(r martini.Router) {
		r.Get("", UserIndex)
		r.Get("/:id", UserShow)
	})

	m.Get("/stats", StatsIndex)
	m.Get("/issues", IssuesIndex)

	return m
}
开发者ID:jakeporter,项目名称:govcode.org,代码行数:35,代码来源:main.go


示例8: CORS

// CORS is a middleware to handle CORS requests
func CORS(h http.Handler) http.Handler {
	f := cors.Allow(&cors.Options{
		AllowAllOrigins: true,
		AllowMethods:    []string{"PUT", "PATCH", "DELETE", "POST"},
	})
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		f(w, r)
		h.ServeHTTP(w, r)
	})
}
开发者ID:Zenithar,项目名称:golang-common,代码行数:11,代码来源:cors.go


示例9: main

func main() {
	var (
		newrelicLicense = os.Getenv("NEWRELIC_LICENSE")
		newrelicName    = os.Getenv("NEWRELIC_NAME")
	)
	if newrelicLicense != "" && newrelicName != "" {
		agent := gorelic.NewAgent()
		agent.Verbose = true
		agent.NewrelicLicense = os.Getenv("NEWRELIC_LICENSE")
		agent.NewrelicName = os.Getenv("NEWRELIC_NAME")
		agent.Run()
	}

	m := martini.Classic()
	m.Get("/", func() string {
		return "Hello world!"
	})

	var logger *log.Logger
	logger = m.Injector.Get(reflect.TypeOf(logger)).Interface().(*log.Logger)

	m.Post("**", func(res http.ResponseWriter, req *http.Request) (int, string) {
		var (
			contentTypeHeader []string
			contentType       string
		)
		contentTypeHeader = req.Header["Content-Type"]
		if len(contentTypeHeader) > 0 {
			contentType = contentTypeHeader[0]
		} else {
			return 400, "Content-Type header is mandatory"
		}
		body, err := ioutil.ReadAll(req.Body)
		if err != nil {
			return 400, "Invalid request body"
		}
		if contentType == "application/x-php" {
			qsa := toMapStringString(req.URL.Query())
			return checkPhp(res, string(body[:]), qsa)
		}
		return 415, "Content-Type not currently supported"
	})

	var corsOrigins = os.Getenv("CORS_ORIGINS")
	if corsOrigins != "" {
		logger.Println("activating CORS: " + corsOrigins)
		m.Use(cors.Allow(&cors.Options{
			AllowOrigins: strings.Split(corsOrigins, ","),
			AllowMethods: []string{"GET", "POST"},
			AllowHeaders: []string{"Origin", "Content-Type"},
		}))
	}

	m.Run()
}
开发者ID:jokeyrhyme,项目名称:omnilint-server,代码行数:55,代码来源:omnilint-server.go


示例10: NewAPI

func NewAPI() *API {
	m := martini.Classic()
	m.Use(render.Renderer())
	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:  []string{"*"},
		AllowMethods:  []string{"POST", "GET"},
		ExposeHeaders: []string{"Content-Length"},
	}))
	m.Use(staticbin.Static("web", Asset))
	return &API{m}
}
开发者ID:henrytrager,项目名称:bitcannon,代码行数:11,代码来源:api.go


示例11: main

func main() {

	if conf, e := LoadConfig("conf/string_keeper.conf"); e != nil {
		if os.IsNotExist(e) {
			fmt.Println("'conf/string_keeper.conf' not exist, it will use default config.")
			keeperConf = DefaultConfig()
		} else {
			fmt.Printf("load config file 'conf/string_keeper.conf' failed, err: %s\n", e.Error())
			os.Exit(1)
		}
	} else {
		keeperConf = conf
	}

	m := martini.Classic()

	m.Post("/", GetBucketString)

	m.Get("/ping", func() string {
		return "pong"
	})

	if cwd, e := os.Getwd(); e != nil {
		fmt.Printf("get current dir failed, err: %s", e.Error())
		os.Exit(1)
	} else if !filepath.IsAbs(cwd) {
		if absPath, e := filepath.Abs(cwd); e != nil {
			fmt.Printf("get current dir abs path failed, err: %s", e.Error())
			os.Exit(1)
			return
		} else {
			resDir = filepath.Join(absPath, "public")
		}
	} else {
		resDir = filepath.Join(cwd, "public")
	}

	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     keeperConf.HTTP.CORS.AllowOrigins,
		AllowMethods:     keeperConf.HTTP.CORS.AllowMethods,
		AllowHeaders:     keeperConf.HTTP.CORS.AllowHeaders,
		ExposeHeaders:    keeperConf.HTTP.CORS.ExposeHeaders,
		AllowCredentials: keeperConf.HTTP.CORS.AllowCerdentials,
	}))

	if keeperConf.ACL.AuthEnabled {
		m.Use(auth.BasicFunc(AuthCheck))
	} else {
		m.Map(auth.User(""))
	}

	m.RunOnAddr(keeperConf.HTTP.Address)
}
开发者ID:cw2018,项目名称:string_keeper,代码行数:53,代码来源:main.go


示例12: SetUpMiddleware

func (app *App) SetUpMiddleware(config *pollr.Config) {
	// Setup CORS
	app.m.Use(cors.Allow(&cors.Options{
		AllowCredentials: true,
		AllowOrigins:     []string{config.WebAddress},
		AllowMethods:     []string{"GET", "POST", "PUT"},
		AllowHeaders:     []string{"Origin", "Content-Type"},
		ExposeHeaders:    []string{"Content-Length"},
	}))

	// Session handling
	app.m.Use(sessions.Sessions("pollr_session", sessions.NewCookieStore([]byte(config.AppSecret))))
}
开发者ID:jshrake,项目名称:pollr,代码行数:13,代码来源:server.go


示例13: main

func main() {
	m := martini.Classic()

	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"PUT", "PATCH", "GET", "POST", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "content-type"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))

	session, err := mgo.Dial("localhost")

	if err != nil {
		panic(err)
	}

	defer session.Close()

	m.Map(session)

	m.Group("/foods", func(r martini.Router) {
		r.Get("", GetFood)
		r.Get("/:id", GetFood)
		r.Get("/queries/:name", GetFoodByName)
		r.Post("/new", binding.Bind(d.Food{}), NewFood)
		r.Put("/update/:id", binding.Bind(d.Food{}), UpdateFood)
		r.Delete("/delete/:id", DeleteFood)
	})

	m.Group("/recipes", func(r martini.Router) {
		r.Get("", GetRecipe)
		r.Get("/:id", GetRecipe)
		r.Post("", binding.Bind(Recipe{}), NewRecipe)
		r.Put("/update/:id", binding.Bind(Recipe{}), UpdateRecipe)
		r.Delete("/delete/:id", DeleteRecipe)
	})

	m.Get("/foodGroup", func() []byte {
		foodGroupDB := session.DB("CNF").C("foodGroup")
		query := foodGroupDB.Find(nil)
		var result []d.FoodGroup
		query.All(&result)
		b, _ := json.Marshal(result)
		return b
	})

	m.Run()
}
开发者ID:EckoEdc,项目名称:cookBookAPI,代码行数:49,代码来源:main.go


示例14: Start

func (h *HTTPService) Start() {
	fmt.Println("Process Dispatcher Listening on Port : 5000")
	m := martini.Classic()
	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE"},
		AllowHeaders:     []string{"securityToken", "Content-Type"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))

	m.Post("/:namespace/:class", handleRequest)

	m.RunOnAddr(":5000")
}
开发者ID:sajeetharan,项目名称:v6engine,代码行数:15,代码来源:HTTPService.go


示例15: init

func init() {
	// Initialize store
	store = *GetStoreSession()

	// Initialize martini
	m = martini.New()

	// Setup martini middleware
	m.Use(martini.Recovery())
	m.Use(martini.Logger())

	// Setup routes
	r := martini.NewRouter()
	r.Get(`/shows`, Authenticate, ApiShowsGetAll)
	r.Get(`/shows/:id`, Authenticate, ApiShowsGetOne)
	r.Put(`/shows/:id`, Authenticate, ApiShowsPutOne)
	r.Get(`/shows/:showId/seasons`, ApiSeasonsGetAllByShow)
	r.Get(`/shows/:showId/seasons/:seasonNumber/episodes`, ApiEpisodesGetAllByShowAndSeason)
	r.Get(`/shows/:showId/seasons/:seasonNumber/episodes/:episodeNumber`, ApiEpisodesGetOneByShowAndSeasonAndEpisode)
	r.Post(`/files`, ApiFilesPost)
	r.Patch(`/files`, ApiProcessFiles)
	r.Get(`/register`, ApiUsersRegister)
	r.Post(`/login`, ApiUsersLogin)
	r.Get(`/rss`, ApiRss)

	// Allow CORS
	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"GET", "POST", "PUT", "PATCH", "DELETE"},
		AllowHeaders:     []string{"Origin", "Content-Type", "X-API-TOKEN"},
		ExposeHeaders:    []string{"Content-Length", "Content-Type"},
		AllowCredentials: true,
	}))
	// Other stuff
	m.Use(func(c martini.Context, w http.ResponseWriter) {
		// Inject JSON Encoder
		c.MapTo(encoder.JsonEncoder{}, (*encoder.Encoder)(nil))
		// Force Content-Type
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
	})

	// Inject database
	m.MapTo(store, (*Store)(nil))
	// Add the router action
	m.Action(r.Handle)
}
开发者ID:geoah,项目名称:42minutes-server-api,代码行数:46,代码来源:main.go


示例16: main

func main() {
	server := martini.Classic()
	server.Use(martini.Static("../public"))
	server.Use(martini.Static("../assets/javascript/app"))
	server.Use(nocache.UpdateCacheHeaders())
	server.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"https://localhost:3000"},
		AllowMethods:     []string{"POST", "GET"},
		AllowHeaders:     []string{"Origin", "Content-Type"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))
	server.Get("/")
	server.Post("/calculator", Calculate)

	log.Fatal(http.ListenAndServe(":3000", server))
}
开发者ID:Prometheus-SCN,项目名称:Prometheus,代码行数:17,代码来源:server.go


示例17: main

func main() {
	m := martini.Classic()
	m.Use(render.Renderer())
	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"*"},
		AllowHeaders:     []string{"Origin"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))

	// 获取订阅列表
	m.Get("/feeds", func(params martini.Params, r render.Render) {
		username := params["username"]
		session := createSession()
		defer session.Close()
		c := session.DB("reader").C("users")
		user := User{}
		c.Find(bson.M{"name": username}).One(&user)
		r.JSON(200, user)
	})

	// 保存订阅列表
	m.Put("/feeds", func(params martini.Params, r render.Render) {
		session := createSession()
		defer session.Close()
		c := session.DB("reader").C("users")
		c.UpdateId(params["_id"], params)
		fmt.Printf(params["_id"])

		//添加new feed到Recourse
		//todo

		r.JSON(200, map[string]interface{}{"result": "ok"})
	})

	m.RunOnAddr(":31001")
	m.Run()

	//TODO
	//GET /feeds/items
	//POST /feeds/items/{id}/read
	//POST /feeds/items/{id}/star
	//POST /feeds/items/{id}/unstar
}
开发者ID:TossShinHwa,项目名称:zReader,代码行数:45,代码来源:main.go


示例18: main

func main() {
	server := martini.Classic()

	server.Use(cors.Allow(&cors.Options{
		AllowOrigins:  []string{"*"},
		AllowMethods:  []string{"GET"},
		AllowHeaders:  []string{"Origin"},
		ExposeHeaders: []string{"Content-Length"},
	}))

	server.Get("/mta-api/subway", func() string {
		var buffer bytes.Buffer
		var r MTAResponse
		var bytes []byte

		resp, err := http.Get("http://www.mta.info/service_status_json/23458509")

		if err != nil {
			buffer.WriteString(err.Error())
		}
		defer resp.Body.Close()

		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			buffer.WriteString(err.Error())
		}

		stringed := string(body[:])
		stringed = strings.Replace(stringed, "\\u0022", "\"", -1)
		stringed = stringed[3 : len(stringed)-1]

		bytes = []byte(stringed)

		e := json.Unmarshal(bytes, &r)
		if e != nil {
			buffer.WriteString(e.Error())
		}

		b, err := json.Marshal(r.Subway)

		return string(b[:])
	})
	server.Run()
}
开发者ID:jroblak,项目名称:mtaapi,代码行数:44,代码来源:mtaapi.go


示例19: initServer

func initServer() {
	// addr := "localhost:7000"
	m := martini.Classic()
	/*
	  f, err := os.OpenFile("server.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
		if err != nil {
			panic(err)
		}
		defer f.Close()
	  m.Map(stdlog.New(f, "[martini]", stdlog.LstdFlags))

	  m.Use(martini.Static(filepath.Join(binRoot, "assets/statics")))
		m.Use(render.Renderer(render.Options{
			Directory:  filepath.Join(binRoot, "assets/template"),
			Extensions: []string{".tmpl", ".html"},
			Charset:    "UTF-8",
			IndentJSON: true,
		})) */

	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"POST", "GET", "DELETE", "PUT"},
		AllowHeaders:     []string{"Origin", "x-requested-with", "Content-Type", "Content-Range", "Content-Disposition", "Content-Description"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: false,
	}))

	// m.Get("/sample/:addr", sample)
	m.Get("/", func() string {
		return "Hello world!"
	})

	m.Get("/voice", voiceHandler)

	/* m.Get("/", func(r render.Render) {
		r.Redirect("/admin")
	}) */

	// m.Run()
	//m.RunOnAddr(addr)
	m.RunOnAddr(":8000")
}
开发者ID:is00hcw,项目名称:gitwork,代码行数:42,代码来源:voice.go


示例20: main

func main() {
	switch {
	case h:
		flag.PrintDefaults()
	default:
		m := martini.Classic()

		m.Use(render.Renderer())

		m.Use(cors.Allow(&cors.Options{
			AllowOrigins: []string{"*"},
			AllowHeaders: []string{"Origin"},
		}))

		m.Get("/user/:id", GetUserLogs)
		m.Get("/repo/:name", GetRepoLogs)

		m.Run()
	}
}
开发者ID:zhangymJLU,项目名称:gitlab-auditor,代码行数:20,代码来源:main.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang encoder.Must函数代码示例发布时间:2022-05-23
下一篇:
Golang binding.Errors类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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