本文整理匯總了Golang中github.com/codegangsta/negroni.NewLogger函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewLogger函數的具體用法?Golang NewLogger怎麽用?Golang NewLogger使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了NewLogger函數的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: 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
}
示例3: 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}
}
示例4: 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)
}
示例5: getNegroniHandlers
func getNegroniHandlers(ctx *RouterContext.RouterContext, router *mux.Router) []negroni.Handler {
tmpArray := []negroni.Handler{}
// fullRecoveryStackMessage := GlobalConfigSettings.Common.DevMode
routerRecoveryWrapper := &tmpRouterRecoveryWrapper{ctx.Logger}
// tmpArray = append(tmpArray, gzip.Gzip(gzip.DefaultCompression))
tmpArray = append(tmpArray, NewRecovery(routerRecoveryWrapper.onRouterRecoveryError)) //recovery.JSONRecovery(fullRecoveryStackMessage))
tmpArray = append(tmpArray, negroni.NewLogger())
if ctx.Settings.IsDevMode() {
middleware := stats.New()
router.HandleFunc("/stats.json", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
stats := middleware.Data()
b, _ := json.Marshal(stats)
w.Write(b)
})
tmpArray = append(tmpArray, middleware)
}
return tmpArray
}
示例6: 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))
}
示例7: main
func main() {
//init datasotre
datastore.Connect(true, false)
defer datastore.Close()
//define routes
m := http.NewServeMux()
m.Handle("/api/", http.StripPrefix("/api", handlers.HandleAPI()))
m.Handle("/", handlers.HandleWEB())
//create negroni middleware
n := negroni.New()
n.Use(negroni.NewRecovery())
n.Use(negroni.NewLogger())
//add security
n.Use(negroni.HandlerFunc(secureMiddleware.HandlerFuncWithNext))
//add static content from public folder, index.html, seo files and favicon
//n.Use(negroni.NewStatic(http.Dir("public")))
//add application handlers
n.UseHandler(m)
//running the server
n.Run(":8000")
}
示例8: 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)
}
示例9: 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)
}
示例10: 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()))
}
示例11: 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}
}
示例12: 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"))
}
示例13: initNegroni
// initialize Negroni (middleware, handler)
func initNegroni(handler http.Handler) *negroni.Negroni {
n := negroni.New()
n.Use(negroni.NewRecovery())
n.Use(negroni.NewLogger())
n.Use(ContentTypeMiddleware())
n.UseHandler(handler)
return n
}
示例14: main
func main() {
n := negroni.New(
negroni.NewRecovery(),
negroni.HandlerFunc(MyMiddleware),
negroni.NewLogger(),
negroni.NewStatic(http.Dir("public")),
)
n.Run(":8080")
}
示例15: main
func main() {
if *hotReload {
// set up file watcher
log.Printf("setting up file watcher for %s\n", *hooksFilePath)
var err error
watcher, err = fsnotify.NewWatcher()
if err != nil {
log.Fatal("error creating file watcher instance", err)
}
defer watcher.Close()
go watchForFileChange()
err = watcher.Add(*hooksFilePath)
if err != nil {
log.Fatal("error adding hooks file to the watcher", err)
}
}
l := negroni.NewLogger()
l.Logger = log.New(os.Stdout, "[webhook] ", log.Ldate|log.Ltime)
negroniRecovery := &negroni.Recovery{
Logger: l.Logger,
PrintStack: true,
StackAll: false,
StackSize: 1024 * 8,
}
n := negroni.New(negroniRecovery, l)
router := mux.NewRouter()
var hooksURL string
if *hooksURLPrefix == "" {
hooksURL = "/{id}"
} else {
hooksURL = "/" + *hooksURLPrefix + "/{id}"
}
router.HandleFunc(hooksURL, hookHandler)
n.UseHandler(router)
if *secure {
log.Printf("starting secure (https) webhook on %s:%d", *ip, *port)
log.Fatal(http.ListenAndServeTLS(fmt.Sprintf("%s:%d", *ip, *port), *cert, *key, n))
} else {
log.Printf("starting insecure (http) webhook on %s:%d", *ip, *port)
log.Fatal(http.ListenAndServe(fmt.Sprintf("%s:%d", *ip, *port), n))
}
}