當前位置: 首頁>>代碼示例>>Golang>>正文


Golang cors.Allow函數代碼示例

本文整理匯總了Golang中github.com/martini-contrib/cors.Allow函數的典型用法代碼示例。如果您正苦於以下問題:Golang Allow函數的具體用法?Golang Allow怎麽用?Golang Allow使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了Allow函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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


注:本文中的github.com/martini-contrib/cors.Allow函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。