本文整理匯總了Golang中github.com/codegangsta/negroni.NewStatic函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewStatic函數的具體用法?Golang NewStatic怎麽用?Golang NewStatic使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了NewStatic函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: 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"))
}
示例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: newServer
func newServer() *http.Server {
n := negroni.New()
// Middlewares
if Settings["environments"].GetBool("log") {
n.Use(negroni.NewLogger())
}
n.UseFunc(recovery())
n.Use(negroni.NewStatic(http.Dir("./public")))
// Setup routes
router := pat.New()
router.Get("/api/v1/:env/driver/:ID", http.HandlerFunc(getDriverLocation))
//router.Post("/api/v1/<resource>", http.HandlerFunc(/*handle func*/))
// Add alive endpoint
// router.Get("/alive", http.HandlerFunc(alive))
// Add the router action
n.UseHandler(router)
Server := &http.Server{
Addr: ":" + Settings["environments"].GetString("server.port"),
Handler: n,
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
MaxHeaderBytes: 1 << 20,
}
return Server
}
示例4: NewApp
// This function is called from main.go and from the tests
// to create a new application.
func NewApp(root string) *App {
CheckEnv()
// Use negroni for middleware
ne := negroni.New()
// Use gorilla/mux for routing
ro := mux.NewRouter()
// Use Render for template. Pass in path to templates folder
// as well as asset helper functions.
re := render.New(render.Options{
Directory: filepath.Join(root, "templates"),
Layout: "layouts/layout",
Extensions: []string{".html"},
Funcs: []template.FuncMap{AssetHelpers(root)},
})
// Establish connection to DB as specificed in database.go
db := NewDB()
// Add middleware to the stack
ne.Use(negroni.NewRecovery())
ne.Use(negroni.NewLogger())
ne.Use(NewAssetHeaders())
ne.Use(negroni.NewStatic(http.Dir("public")))
ne.UseHandler(ro)
// Return a new App struct with all these things.
return &App{ne, ro, re, db}
}
示例5: serverRun
func serverRun(cmd *cobra.Command, args []string) {
// MongoDB setup
CreateUniqueIndexes()
// Web Server Setup
CreateStore()
webRouter := CreateWebRouter()
teamRouter := CreateTeamRouter()
app := negroni.New()
webRouter.PathPrefix("/").Handler(negroni.New(
negroni.HandlerFunc(RequireLogin),
negroni.Wrap(teamRouter),
))
app.Use(negroni.NewLogger())
app.Use(negroni.NewStatic(http.Dir("static")))
app.Use(negroni.HandlerFunc(CheckSessionID))
app.UseHandler(webRouter)
l := log.New(os.Stdout, "[negroni] ", 0)
http_port := viper.GetString("server.http_port")
https_port := viper.GetString("server.https_port")
cert := viper.GetString("server.cert")
key := viper.GetString("server.key")
l.Printf("Server running at: https://%s:%s", viper.GetString("server.ip"), https_port)
go http.ListenAndServe(":"+http_port, http.HandlerFunc(redir))
l.Fatal(http.ListenAndServeTLS(":"+https_port, cert, key, app))
}
示例6: 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))
}
示例7: 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))
}
示例8: 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)
}
示例9: 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}
}
示例10: main
func main() {
conf.Parse()
restrict.ReadCryptoKey("keys/app.rsa")
router := mux.NewRouter()
router.HandleFunc("/users", GetUserHandler).Methods("GET")
router.HandleFunc("/users/login", LoginHandler).Methods("POST")
router.HandleFunc("/users/register", RegisterHandler).Methods("POST")
router.HandleFunc("/classes", restrict.R(CreateClassHandler)).Methods("POST")
router.HandleFunc("/classes", restrict.R(GetClassesHandler)).Methods("GET")
router.HandleFunc("/classes/{class_id}/workshops", restrict.R(CreateWorkshopHandler)).Methods("POST")
router.HandleFunc("/classes/{class_id}/workshops/{workshop_id}/pages", restrict.R(CreateWorkshopPageHandler)).Methods("POST")
router.HandleFunc("/classes/{class_id}/workshops/{workshop_id}/pages", restrict.R(GetWorkshopPagesHandler)).Methods("GET")
router.HandleFunc("/classes/{class_id}/workshops/{workshop_id}/pages/{page_id}/edit", restrict.R(EditPageHandler)).Methods("POST")
router.HandleFunc("/classes/{class_id}/workshops/{workshop_id}", restrict.R(GetWorkshopHandler)).Methods("GET")
router.HandleFunc("/classes/{class_id}/workshops/{workshop_id}", restrict.R(EditWorkshopHandler)).Methods("PUT")
router.HandleFunc("/classes/{class_id}/workshops/{workshop_id}", restrict.R(DeleteWorkshopHandler)).Methods("DELETE")
router.HandleFunc("/classes/{class_id}/workshops", restrict.R(GetWorkshopsHandler)).Methods("GET")
router.HandleFunc("/classes/{class_id}/students", restrict.R(GetStudentHandler)).Methods("GET")
router.HandleFunc("/classes/{class_id}/image", restrict.R(SetClassImageHandler)).Methods("POST")
router.HandleFunc("/classes/{class_id}/admin/students", restrict.R(AddUserToClassHandler)).Methods("POST")
n := negroni.New()
n.Use(negroni.NewStatic(http.Dir("static")))
n.Use(negroni.NewLogger())
n.UseHandler(router)
models.InitDB(*dbFile)
http.ListenAndServe("localhost:8080", n)
}
示例11: main
func main() {
settings := evergreen.GetSettingsOrExit()
if settings.Ui.LogFile != "" {
evergreen.SetLogger(settings.Ui.LogFile)
}
db.SetGlobalSessionProvider(db.SessionFactoryFromConfig(settings))
home := evergreen.FindEvergreenHome()
userManager, err := auth.LoadUserManager(settings.AuthConfig)
if err != nil {
fmt.Println("Failed to create user manager:", err)
os.Exit(1)
}
cookieStore := sessions.NewCookieStore([]byte(settings.Ui.Secret))
uis := ui.UIServer{
nil, // render
settings.Ui.Url, // RootURL
userManager, // User Manager
*settings, // mci settings
cookieStore, // cookiestore
nil, // plugin panel manager
}
router, err := uis.NewRouter()
if err != nil {
fmt.Println("Failed to create router:", err)
os.Exit(1)
}
webHome := filepath.Join(home, "public")
functionOptions := ui.FuncOptions{webHome, settings.Ui.HelpUrl, true, router}
functions, err := ui.MakeTemplateFuncs(functionOptions, settings.SuperUsers)
if err != nil {
fmt.Println("Failed to create template function map:", err)
os.Exit(1)
}
uis.Render = render.New(render.Options{
Directory: filepath.Join(home, ui.WebRootPath, ui.Templates),
DisableCache: !settings.Ui.CacheTemplates,
Funcs: functions,
})
err = uis.InitPlugins()
if err != nil {
fmt.Println("WARNING: Error initializing plugins:", err)
}
n := negroni.New()
n.Use(negroni.NewStatic(http.Dir(webHome)))
n.Use(ui.NewLogger())
n.Use(negroni.HandlerFunc(ui.UserMiddleware(userManager)))
n.UseHandler(router)
graceful.Run(settings.Ui.HttpListenAddr, requestTimeout, n)
evergreen.Logger.Logf(slogger.INFO, "UI server cleanly terminated")
}
示例12: main
func main() {
n := negroni.Classic()
n.Use(negroni.NewStatic(http.Dir(".")))
// listen on port
n.Run(":8080")
}
示例13: StaticPathFallback
func StaticPathFallback(path string) http.Handler {
return negroni.New(
negroni.NewStatic(http.Dir(path)),
negroni.Wrap(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.URL.Path = "/"
http.FileServer(http.Dir(path)).ServeHTTP(w, r)
})))
}
示例14: setupNegroni
func (srv *Server) setupNegroni() {
srv.log.Debug("setting up negroni")
srv.n = negroni.New()
srv.n.Use(negroni.NewRecovery())
srv.n.Use(negronilogrus.NewMiddleware())
srv.n.Use(negroni.NewStatic(http.Dir("public")))
srv.n.UseHandler(srv.Router)
}
示例15: main
func main() {
// Load the configuration.
err := envconfig.Process("elwinar", &configuration)
if err != nil {
log.Fatalln("unable to read the configuration from env:", err)
}
// Open the database connection.
database, err = sqlx.Connect("sqlite3", configuration.Database)
if err != nil {
log.Fatalln("unable to open the database:", err)
}
// Initialize the router.
router := httprouter.New()
// Add the front-office handlers.
router.GET("/", Index)
router.GET("/read", List)
router.GET("/article/:slug", View)
router.GET("/fortune", Fortune)
router.GET("/sitemap.xml", Sitemap)
// Add the back-office handlers.
router.GET("/login", Login)
router.POST("/login", Authenticate)
router.GET("/logout", Logout)
router.GET("/write", Write)
router.POST("/write", Create)
router.GET("/article/:slug/edit", Edit)
router.POST("/article/:slug/edit", Update)
router.GET("/article/:slug/delete", Delete)
router.GET("/article/:slug/publish", Publish)
router.GET("/article/:slug/unpublish", Unpublish)
// Initialize the server middleware stack.
stack := negroni.New()
stack.Use(gzip.Gzip(gzip.DefaultCompression))
stack.Use(negroni.NewRecovery())
stack.Use(negroni.NewStatic(http.Dir(configuration.Public)))
stack.Use(sessions.Sessions("elwinar", cookiestore.New([]byte(configuration.Secret))))
stack.UseHandler(router)
// Initialize the HTTP server.
server := &graceful.Server{
Timeout: 1 * time.Second,
Server: &http.Server{
Addr: fmt.Sprintf(":%d", configuration.Port),
Handler: stack,
},
}
// Run the server.
err = server.ListenAndServe()
if err != nil {
log.Fatalln("unable to run the server:", err)
}
}