本文整理汇总了Golang中github.com/rs/cors.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了New函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
}
}
示例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))
}
示例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
}
示例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)
}
示例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)
}
示例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)})
}
示例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)
}
示例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))
}
示例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
}
示例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
}
示例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
}
示例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)
}
}
示例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
}
示例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()
}
示例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)
}
}