本文整理匯總了Golang中github.com/codegangsta/negroni.NewRecovery函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewRecovery函數的具體用法?Golang NewRecovery怎麽用?Golang NewRecovery使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了NewRecovery函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: main
func main() {
var err error
db, err = sqlx.Connect("postgres", "user=postgres password=postgres dbname=messenger sslmode=disable")
if err != nil {
log.Fatalln(err)
}
CreateSchema(false)
r := mux.NewRouter()
authBase := mux.NewRouter()
apiBase := mux.NewRouter()
auth := authBase.PathPrefix("/auth").Subrouter()
api := apiBase.PathPrefix("/api").Subrouter()
r.PathPrefix("/auth").Handler(negroni.New(
negroni.NewRecovery(),
negroni.NewLogger(),
negroni.Wrap(authBase),
))
jwtSecret = "a very secret string"
// must be authenticated to use api routes
jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
return []byte(jwtSecret), nil
},
SigningMethod: jwt.SigningMethodHS256,
UserProperty: "jwt_user",
})
r.PathPrefix("/api").Handler(negroni.New(
negroni.NewRecovery(),
negroni.NewLogger(),
negroni.HandlerFunc(jwtMiddleware.HandlerWithNext),
negroni.Wrap(apiBase),
))
// used to check if server is live
auth.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "pong")
}).Methods("POST")
auth.Path("/signup").HandlerFunc(Signup).Methods("POST")
auth.Path("/login").HandlerFunc(Login).Methods("POST")
api.Path("/messages").HandlerFunc(NewMessage).Methods("POST")
api.HandleFunc("/{user}/messages", GetUsersMessages).Methods("GET")
log.Fatal(http.ListenAndServe(":8080", r))
}
示例2: main
func main() {
router := mux.NewRouter()
router.HandleFunc(xmlEndpoint+"/alerts", func(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Access-Control-Allow-Origin", "*")
}).Methods("OPTIONS")
//router.HandleFunc(xmlEndpoint+"/alerts", alertPost).Methods("POST")
//router.HandleFunc(xmlEndpoint+"/alerts", alertsGet).Methods("GET")
router.HandleFunc(xmlEndpoint+"/alerts/{id}", alertGet).Methods("GET")
router.HandleFunc(jsonEndpoint+"/alerts", alertPostJson).Methods("POST")
router.HandleFunc(jsonEndpoint+"/alerts", alertsGetJson).Methods("GET")
router.HandleFunc(jsonEndpoint+"/alerts/{id}", alertGetJson).Methods("GET")
// router.HandleFunc("/alerts/{id}", alertPost).Methods("POST")
router.HandleFunc(xmlEndpoint+"/feed", getAtomFeed)
//router.HandleFunc("/mdc", DrgHandler).Methods("GET")
// router.HandleFunc("/", HomeHandler)
n := negroni.New(negroni.NewRecovery(), NewLogger(), negroni.NewStatic(http.Dir("dist")))
n.UseHandler(router)
n.Run(qcapListen)
}
示例3: main
func main() {
// render
r := render.New(render.Options{})
// middleware
n := negroni.New(
negroni.NewLogger(),
negroni.NewRecovery(),
)
// database
sess, err := db.Open(sqlite.Adapter, sqlite.ConnectionURL{
Database: "test.db",
})
if err != nil {
log.Fatal(err)
}
defer sess.Close()
// router
router := httprouter.New()
groupsController := controllers.NewGroupsController(r, sess)
router.GET("/api/v1/groups.json", groupsController.Index)
router.POST("/api/v1/groups.json", groupsController.Create)
n.UseHandler(router)
n.Run(":" + strconv.Itoa(getPort()))
}
示例4: 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
}
示例5: main
func main() {
fmt.Printf("hyperion-dashboard%s\n", buildVersion)
httpAddr := flag.String("http-address", "127.0.0.1:12300", "<addr>:<port> to listen on")
dsn := flag.String("db", "", "Database source name")
flag.Parse()
dataSource := *dsn
if dataSource == "" {
if os.Getenv("HYPERION_DB") != "" {
dataSource = os.Getenv("HYPERION_DB")
}
}
if dataSource == "" {
flag.Usage()
log.Fatal("--db or HYPERION_DB not found")
}
db, err := NewDBConn(dataSource)
if err != nil {
log.Fatal(err.Error())
}
router := mux.NewRouter()
router.HandleFunc("/", db.RecordsHandler)
recovery := negroni.NewRecovery()
logger := negroni.NewLogger()
n := negroni.New(recovery, logger)
n.UseHandler(router)
n.Run(*httpAddr)
}
示例6: StartServer
func StartServer() {
rest.P()
// Log to file
f, err := os.OpenFile("logs/arkeogis.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("Error opening log file: %v", err)
}
defer f.Close()
log.SetOutput(f)
// Configure Negroni and start server
Negroni := negroni.New(
negroni.NewRecovery(),
negroni.HandlerFunc(crossDomainMiddleware),
NewLogger(),
negroni.NewStatic(http.Dir(config.WebPath)),
)
Negroni.UseHandler(routes.MuxRouter)
/* DEBUG SENDING MAIL
fmt.Println("SENDING MAIL")
errrr := mail.Send([]string{"[email protected]"}, "pouet", "poeut", "fr")
if errrr != nil {
log.Println(errors.ErrorStack(errrr))
}
fmt.Println("starting web server...")
*/
Negroni.Run(":" + strconv.Itoa(config.Main.Server.Port))
}
示例7: main
func main() {
c, err := myrpc.Dial("tcp", checkEnv("VEIL_LISTENER"))
check(err)
h := handlers.New(&handlers.H{C: c})
r := mux.NewRouter()
r.HandleFunc("/api/version", h.Version).Methods("GET")
r.HandleFunc("/api/payloads", h.Payloads).Methods("GET")
r.HandleFunc("/api/options", h.PayloadOptions).Methods("GET")
r.HandleFunc("/api/generate", h.Generate).Methods("POST")
n := negroni.New()
n.Use(negroni.NewLogger())
n.Use(negroni.NewRecovery())
n.Use(negroni.NewStatic(http.Dir(checkEnv("VEIL_OUTPUT_DIR"))))
n.Use(auth.Basic(checkEnv("ADMIN_USER"), checkEnv("ADMIN_PASS")))
n.Use(negroni.NewStatic(http.Dir("public")))
n.Use(negroni.HandlerFunc(func(w http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
if req.Method != "POST" {
next(w, req)
return
}
if !strings.Contains(req.Header.Get("content-type"), "application/json") {
h.JSON400(w, errors.New("Content-Type must be application/json"))
return
}
next(w, req)
}))
n.UseHandler(r)
n.Run(checkEnv("SERVER_LISTENER"))
}
示例8: New
// New creates a REST API server with a given config
func New(cfg *Config) (*Server, error) {
// pull a few parameters from the configuration passed in by snapd
https := cfg.HTTPS
cpath := cfg.RestCertificate
kpath := cfg.RestKey
s := &Server{
err: make(chan error),
killChan: make(chan struct{}),
addrString: cfg.Address,
}
if https {
var err error
s.snapTLS, err = newtls(cpath, kpath)
if err != nil {
return nil, err
}
protocolPrefix = "https"
}
restLogger.Info(fmt.Sprintf("Configuring REST API with HTTPS set to: %v", https))
s.n = negroni.New(
NewLogger(),
negroni.NewRecovery(),
negroni.HandlerFunc(s.authMiddleware),
)
s.r = httprouter.New()
// Use negroni to handle routes
s.n.UseHandler(s.r)
return s, nil
}
示例9: main
func main() {
// Config
// ----------------------------
// Set the port.
port := os.Getenv("PORT")
if port == "" {
port = "3000"
}
// Object Graph
// ----------------------------
app := app.Ioc{}
app.ConfigService = services.NewConfigService()
app.DatabaseService = services.NewDatabaseService(&app)
app.DaysController = controllers.NewDaysController(&app)
// Router
// ----------------------------
router := routes.NewRouter(&app)
// Do we want to use negroni again? Meh ... what about another way to do recovery
n := negroni.New(
negroni.NewRecovery(),
negroni.NewLogger(),
)
n.UseHandler(router)
// Server
// ----------------------------
n.Run(":" + port)
}
示例10: main
func main() {
// Setup Routes
router := httprouter.New()
router.RedirectTrailingSlash = false
router.RedirectFixedPath = false
router.POST("/", func(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
// simulate API calls, etc...
time.Sleep(300 * time.Millisecond)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Write([]byte("{ \"code\":3.14159265359, \"description\":\"HI!\" }"))
})
// Setup Server
n := negroni.New()
n.Use(negroni.NewRecovery())
n.UseHandler(router)
// start server
port := os.Getenv("PORT")
if port == "" {
port = "3000"
}
n.Run(":" + port)
}
示例11: configureHttpAndListen
func configureHttpAndListen(config *AppConfig, db gorm.DB) {
// register routes
r := render.New(render.Options{})
h := DBHandler{db: &db, r: r}
router := mux.NewRouter()
router.HandleFunc("/api/schedules", h.schedulesIndexHandler).Methods("GET")
router.HandleFunc("/api/schedules", h.scheduleCreateHandler).Methods("POST")
router.HandleFunc("/api/schedules/{id:[0-9]+}", h.scheduleShowHandler).Methods("GET")
router.HandleFunc("/api/schedules/{id:[0-9]+}", h.scheduleUpdateHandler).Methods("PUT", "PATCH")
router.HandleFunc("/api/schedules/{id:[0-9]+}", h.scheduleDeleteHandler).Methods("DELETE")
router.HandleFunc("/api/cards", h.cardsIndexHandler).Methods("GET")
router.HandleFunc("/api/cards", h.cardCreateHandler).Methods("POST")
router.HandleFunc("/api/cards/{id:[0-9]+}", h.cardShowHandler).Methods("GET")
router.HandleFunc("/api/cards/{id:[0-9]+}", h.cardUpdateHandler).Methods("PUT", "PATCH")
router.HandleFunc("/api/cards/{id:[0-9]+}", h.cardDeleteHandler).Methods("DELETE")
router.HandleFunc("/api/logs", h.logsIndexHandler).Methods("GET")
n := negroni.New(
negroni.NewRecovery(),
negroni.NewStatic(http.Dir(config.AssetPath)),
)
n.Use(auth.Basic(config.Authentication.Username, config.Authentication.Password))
n.UseHandler(router)
n.Run(":" + config.Port)
}
示例12: NewApp
func NewApp() *App {
db := newDB()
// Use negroni for middleware
ne := negroni.New(
negroni.NewRecovery(),
negroni.NewLogger(),
negroni.NewStatic(http.Dir("public")),
)
// Use gorilla/mux for routing
ro := mux.NewRouter()
// Set StrictSlash to allow /things/ to automatically redirect to /things
ro.StrictSlash(true)
// Use Render for template. Pass in path to templates folder
// as well as asset helper functions.
re := render.New(render.Options{
Layout: "layouts/layout",
Extensions: []string{".html"},
})
ne.UseHandler(ro)
return &App{ne, ro, re, db}
}
示例13: StartServer
func StartServer(listenAddr string, cache job.JobCache, db job.JobDB) error {
r := mux.NewRouter()
SetupApiRoutes(r, cache, db)
n := negroni.New(negroni.NewRecovery(), &middleware.Logger{log})
n.UseHandler(r)
return http.ListenAndServe(listenAddr, n)
}
示例14: main
func main() {
m := martini.Classic()
m.Get("/", func() string {
return "Hello world!\n"
})
go m.Run()
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "Hello world!\n")
})
// Use the default middleware.
n := negroni.New(negroni.NewRecovery())
// ... Add any other middlware here
// add the router as the last handler in the stack
n.UseHandler(mux)
go n.Run(":3001")
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello world!\n")
})
log.Fatal(http.ListenAndServe(":3002", nil))
}
示例15: main
func main() {
cfg.MustLoad()
listeningAddr := ":" + cfg.Server.Port
router := mux.NewRouter().PathPrefix(cfg.Server.API.Prefix).Subrouter()
db, err := pg.NewSession(cfg.DB.ConnectionURL())
if err != nil {
log.Fatalf("Unable to connect to database: %s", err)
}
vars := map[string]interface{}{"db": db}
err = ctx.Init(router, cfg.Server.API.PrivKey, cfg.Server.API.PubKey, vars)
if err != nil {
log.Fatalf("Unable to configure API: %s", err)
}
server := negroni.New(
negroni.NewRecovery(),
negroni.HandlerFunc(WebLogger),
negroni.NewStatic(http.Dir(cfg.Server.Frontend.Path)),
)
server.UseHandler(router)
log.Infof("Listening on address: %s", listeningAddr)
log.Fatal(http.ListenAndServe(listeningAddr, server))
}