本文整理汇总了Golang中github.com/rs/cors.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了New函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: main
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)
}
}
开发者ID:yetone,项目名称:rest-layer,代码行数:34,代码来源:main.go
示例2: main
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))
}
开发者ID:breathingdust,项目名称:house.api,代码行数:30,代码来源:server.go
示例3: Start
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
}
开发者ID:hiroshi1tanaka,项目名称:gethkey,代码行数:31,代码来源:http.go
示例4: NewAPI
// 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)
}
开发者ID:JordietYahii,项目名称:netlify-git-api,代码行数:30,代码来源:api.go
示例5: main
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)
}
开发者ID:fiatjaf,项目名称:imagebase64er.alhur.es,代码行数:31,代码来源:web.go
示例6: main
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)})
}
开发者ID:newtechfellas,项目名称:IamOkApis,代码行数:27,代码来源:main.go
示例7: Handler
// 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)
}
开发者ID:wjarek,项目名称:gcm-playground,代码行数:28,代码来源:server.go
示例8: main
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))
}
开发者ID:mehulsbhatt,项目名称:sample_bank_server,代码行数:26,代码来源:main.go
示例9: Serve
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
}
开发者ID:auroralaboratories,项目名称:corona-api,代码行数:32,代码来源:api.go
示例10: Start
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
}
开发者ID:gnidan,项目名称:foodtastechess,代码行数:35,代码来源:server.go
示例11: StartHttp
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
}
开发者ID:ssonneborn22,项目名称:go-ethereum,代码行数:31,代码来源:http.go
示例12: main
// 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)
}
}
开发者ID:Wodan71,项目名称:workshop-dbg,代码行数:32,代码来源:main.go
示例13: NewNegHandler
// 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
}
开发者ID:vijaykanthm28,项目名称:vertice,代码行数:28,代码来源:neghandler.go
示例14: main
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()
}
开发者ID:tiare-lava,项目名称:invite-api,代码行数:34,代码来源:main.go
示例15: Example
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)
}
}
开发者ID:rs,项目名称:rest-layer-mongo,代码行数:29,代码来源:example_test.go
示例16: main
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:5000"},
})
// start server
log.Fatal(http.ListenAndServe(":8000", c.Handler(router)))
log.Println("Listening @ localhost:8000")
}
开发者ID:constellates,项目名称:confessions-api,代码行数:26,代码来源:main.go
示例17: StartHttp
// 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
}
开发者ID:codeaudit,项目名称:shift,代码行数:30,代码来源:http.go
示例18: setupMiddleware
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)),
}
}
开发者ID:MustWin,项目名称:go-base,代码行数:26,代码来源:main.go
示例19: setup
// 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)
}
开发者ID:glycerine,项目名称:origins,代码行数:34,代码来源:main.go
示例20: main
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)
}
开发者ID:demipixel,项目名称:Helen,代码行数:60,代码来源:main.go
注:本文中的github.com/rs/cors.New函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论