本文整理汇总了Golang中github.com/gorilla/handlers.LoggingHandler函数的典型用法代码示例。如果您正苦于以下问题:Golang LoggingHandler函数的具体用法?Golang LoggingHandler怎么用?Golang LoggingHandler使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了LoggingHandler函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
r := mux.NewRouter()
conn, err := db.Connect(os.Getenv("DB_URL"), os.Getenv("DB_NAME"))
if err != nil {
log.Fatal(err)
}
defer conn.Close()
r.Handle("/register.json", controllers.Register(conn)).Methods("POST")
r.Handle("/login.json", controllers.Login(conn)).Methods("POST")
r.Handle("/me.json", controllers.Me(conn)).Methods("GET")
r.Handle("/devices.json", controllers.RegisterDevice(conn)).Methods("PUT")
r.Handle("/listings.json", controllers.Listings(conn)).Methods("GET")
r.Handle("/listings.json", controllers.CreateListing(conn)).Methods("POST")
r.Handle("/listings/{id}.json", controllers.Listing(conn)).Methods("GET")
r.Handle("/listings/{id}/rent.json", controllers.Rent(conn)).Methods("POST")
r.Handle("/rentals.json", controllers.Rentals(conn)).Methods("GET")
r.Handle("/rentals/{id}.json", controllers.Rental(conn)).Methods("GET")
r.Handle("/rentals/{id}/confirm.json", controllers.ConfirmRental(conn)).Methods("PUT")
r.Handle("/rentals/{id}/deny.json", controllers.DenyRental(conn)).Methods("PUT")
r.Handle("/search.json", controllers.Search(conn)).Methods("GET")
if os.Getenv("ENV") == "production" {
log.Fatal(http.ListenAndServeTLS(":"+os.Getenv("PORT"),
os.Getenv("SSL_CERT_PATH"), os.Getenv("SSL_KEY_PATH"), handlers.LoggingHandler(os.Stdout, r)))
} else {
log.Fatal(http.ListenAndServe(":"+os.Getenv("PORT"), handlers.LoggingHandler(os.Stdout, r)))
}
}
开发者ID:haystackapp,项目名称:haystack-api,代码行数:33,代码来源:haystack-api.go
示例2: main
func main() {
db := sqlx.MustOpen("sqlite3", ":memory:")
db.MustExec(`CREATE TABLE Products (
id INTEGER PRIMARY KEY,
name TEXT
);
INSERT INTO Products VALUES (1, 'TV');
INSERT INTO Products VALUES (2, 'Microwave');`)
inventory := &DatabaseInventoryRepository{db}
env := &Env{
inventory: inventory,
decoder: schema.NewDecoder(),
}
r := mux.NewRouter()
r.Handle("/products", handlers.LoggingHandler(os.Stdout, Handler{env, ProductsHandler}))
r.Handle("/products/search", handlers.LoggingHandler(os.Stdout, Handler{env, SearchHandler}))
r.Handle("/docs/", http.StripPrefix("/docs/", http.FileServer(http.Dir("docs"))))
http.ListenAndServe(":8080", r)
}
开发者ID:dimiro1,项目名称:experiments,代码行数:25,代码来源:main.go
示例3: main
func main() {
if os.Getenv("MEMCACHED") == "" {
log.Println("MEMCACHED environment variable must be specified")
os.Exit(1)
}
mc := memcached{memcache.New(os.Getenv("MEMCACHED"))}
mx := mux.NewRouter()
// GET secret
mx.HandleFunc("/secret/{uuid:([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})}",
func(response http.ResponseWriter, request *http.Request) {
getHandler(response, request, mc)
}).Methods("GET")
// Check secret status
mx.HandleFunc("/secret/{uuid:([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})}",
func(response http.ResponseWriter, request *http.Request) {
messageStatus(response, request, mc)
}).Methods("HEAD")
// Save secret
mx.HandleFunc("/secret", func(response http.ResponseWriter, request *http.Request) {
saveHandler(response, request, mc)
}).Methods("POST")
// Serve static files
mx.PathPrefix("/").Handler(http.FileServer(http.Dir("public")))
log.Println("Starting yopass. Listening on port 1337")
if os.Getenv("TLS_CERT") != "" && os.Getenv("TLS_KEY") != "" {
// Configure TLS with sane ciphers
config := &tls.Config{MinVersion: tls.VersionTLS12,
PreferServerCipherSuites: true,
CipherSuites: []uint16{
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_RSA_WITH_AES_128_CBC_SHA,
tls.TLS_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
}}
server := &http.Server{Addr: ":1337",
Handler: handlers.LoggingHandler(os.Stdout, mx), TLSConfig: config}
log.Fatal(server.ListenAndServeTLS(os.Getenv("TLS_CERT"), os.Getenv("TLS_KEY")))
} else {
log.Fatal(http.ListenAndServe(":1337", handlers.LoggingHandler(os.Stdout, mx)))
}
}
开发者ID:vlarsen,项目名称:yopass,代码行数:49,代码来源:yopass.go
示例4: main
func main() {
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
http.Handle("/", handlers.LoggingHandler(os.Stderr, http.FileServer(http.Dir("."))))
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
defer conn.Close()
for {
t, msg, err := conn.ReadMessage()
if err != nil {
log.Println(err)
return
}
log.Println("Received:", string(msg))
err = conn.WriteMessage(t, msg)
if err != nil {
log.Println(err)
return
}
}
})
host := "localhost:3030"
log.Printf("http://%v", host)
log.Fatal(http.ListenAndServe(host, nil))
}
开发者ID:jakecoffman,项目名称:polymer-basics,代码行数:32,代码来源:server.go
示例5: main
func main() {
if os.Getenv("BASE_URL") == "" {
log.Fatal("BASE_URL environment variable must be set")
}
if os.Getenv("DB_PATH") == "" {
log.Fatal("DB_PATH environment variable must be set")
}
db := sqlite{Path: path.Join(os.Getenv("DB_PATH"), "db.sqlite")}
db.Init()
baseURL := os.Getenv("BASE_URL")
if !strings.HasSuffix(baseURL, "/") {
baseURL += "/"
}
r := mux.NewRouter()
r.HandleFunc("/save",
func(response http.ResponseWriter, request *http.Request) {
encodeHandler(response, request, db, baseURL)
}).Methods("POST")
r.HandleFunc("/{id}", func(response http.ResponseWriter, request *http.Request) {
decodeHandler(response, request, db)
})
r.PathPrefix("/").Handler(http.FileServer(http.Dir("public")))
log.Println("Starting server on port :1337")
log.Fatal(http.ListenAndServe(":1337", handlers.LoggingHandler(os.Stdout, r)))
}
开发者ID:jhaals,项目名称:url-shortener,代码行数:28,代码来源:main.go
示例6: main
func main() {
counter, err := NewPostgresCounter(os.Getenv("POSTGRES_URL"))
if err != nil {
log.Printf("Error initializing counter: %#v", err)
os.Exit(1)
}
router := mux.NewRouter().StrictSlash(false)
router.HandleFunc("/", renderHandler(counter))
router.HandleFunc("/index.html", renderHandler(counter))
router.HandleFunc("/counter", counterHandler(counter))
router.PathPrefix("/").Handler(http.FileServer(http.Dir("./static")))
loggedRouter := handlers.LoggingHandler(os.Stdout, router)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
log.Printf("Server listening on port: %s", port)
http.ListenAndServe(":"+port, loggedRouter)
}
开发者ID:stigkj,项目名称:counter,代码行数:25,代码来源:main.go
示例7: main
func main() {
http.HandleFunc("/favicon.ico", iconHandler)
indexHandler := http.HandlerFunc(index)
aboutHandler := http.HandlerFunc(about)
logFile, err := os.OpenFile("server.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
panic(err)
}
http.Handle("/", handlers.LoggingHandler(logFile, handlers.CompressHandler(indexHandler)))
http.Handle("/about", handlers.LoggingHandler(logFile, handlers.CompressHandler(aboutHandler)))
server := &http.Server{
Addr: ":8080",
}
log.Println("Listening...")
server.ListenAndServe()
}
开发者ID:yourchanges,项目名称:go-web,代码行数:16,代码来源:gorillahandlers.go
示例8: main
func main() {
log.Println("Starting journlr...")
var err error
db, err = sql.Open("postgres", os.Getenv("JOURNLR_DB"))
if err != nil {
log.Fatal("No database for journl")
}
r := mux.NewRouter()
r.HandleFunc("/", indexHandler).Methods("GET")
r.HandleFunc("/receive", receiveHandler).Methods("POST")
// make is used to construct a channel otherwise nothing can be put into it.
mailgunStorage = make(chan receiveMsg)
// go keyword here is used to make this a goroutine. This is a
// lightweight thread that doesn't block execution. If we
// expect heavy traffic we can start 5 of these and they'd all
// go and process reading off of the mailgunStorage channel.
go fetchEmails()
http.ListenAndServe(":80", handlers.LoggingHandler(os.Stdout, r))
}
开发者ID:abhiyerra,项目名称:presentations,代码行数:26,代码来源:server7.go
示例9: main
func main() {
flag.Parse()
setupLogging(*HTTPLogLocation)
log.Printf("Now serving on http://localhost:%d\n", *port)
runtime.GOMAXPROCS(runtime.NumCPU())
session, err := r.Connect(*DBConnection, "urls")
if err != nil {
log.Fatal(err)
}
defer session.Close()
router := mux.NewRouter()
// UUID format
router.HandleFunc("/{key:[a-z0-9-]+}", func(w http.ResponseWriter, request *http.Request) {
views.EmbiggenHandler(w, request, session)
}).Methods("GET")
router.HandleFunc("/", func(w http.ResponseWriter, request *http.Request) {
views.ShortenHandler(w, request, session)
}).Methods("POST")
router.HandleFunc("/", views.IndexHandler).Methods("GET")
http.Handle("/", router)
err = http.ListenAndServe(fmt.Sprintf(":%d", *port), handlers.LoggingHandler(HTTPLogger, http.DefaultServeMux))
if err != nil {
log.Fatal(err)
}
}
开发者ID:nickpresta,项目名称:shorter,代码行数:29,代码来源:main.go
示例10: main
func main() {
db := sqlx.MustConnect("sqlite3", ":memory:")
if err := createFooTable(db); err != nil {
log.Fatal("couldn't create table: ", err)
}
for i := 0; i < 10; i++ {
id, err := insertFoo(db, "hello world "+strconv.Itoa(i))
if err != nil {
log.Fatal("failed to insert value: ", err)
}
log.Print("inserted foo record ", id)
}
h := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fooListEndpoint(w, r, &FooStore{db: db})
}))
h = handlers.LoggingHandler(os.Stdout, h)
h = handlers.ContentTypeHandler(h, "application/json")
http.Handle("/foo/", h)
flag.Parse()
log.Print("starting http server on ", *addr)
if err := http.ListenAndServe(*addr, nil); err != nil {
log.Printf("http server failed: ", err)
}
}
开发者ID:peefourtee,项目名称:godatabasesql,代码行数:29,代码来源:api.go
示例11: loggingHandler
func loggingHandler(next http.Handler) http.Handler {
logFile, err := os.OpenFile("server.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0777)
if err != nil {
panic(err)
}
return handlers.LoggingHandler(logFile, next)
}
开发者ID:yourchanges,项目名称:go-web,代码行数:7,代码来源:alice.go
示例12: main
func main() {
var (
socksProxy = flag.String("socks-proxy", "", "Use specified SOCKS proxy (e.g. localhost:2323)")
fleetEndpoint = flag.String("fleetEndpoint", "", "Fleet API http endpoint: `http://host:port`")
whitelist = flag.String("timerBasedServices", "", "List of timer based services separated by a comma: deployer.service,image-cleaner.service,tunnel-register.service")
)
flag.Parse()
fleetAPIClient, err := newFleetAPIClient(*fleetEndpoint, *socksProxy)
if err != nil {
panic(err)
}
wl := strings.Split(*whitelist, ",")
log.Printf("whitelisted services: %v", wl)
wlRegexp := make([]*regexp.Regexp, len(wl))
for i, s := range wl {
wlRegexp[i] = regexp.MustCompile(s)
}
handler := fleetUnitHealthHandler(fleetAPIClient, fleetUnitHealthChecker{wlRegexp})
r := mux.NewRouter()
r.HandleFunc("/", handler)
r.HandleFunc("/__health", handler)
err = http.ListenAndServe(":8080", handlers.LoggingHandler(os.Stdout, r))
if err != nil {
panic(err)
}
}
开发者ID:Financial-Times,项目名称:coco-fleet-unit-healthcheck,代码行数:30,代码来源:fleet-unit-healthcheck.go
示例13: main
func main() {
directory := flag.String("directory", "/usr/local/rct", "Path to the folder storing RCT experiment data")
templateDirectory := flag.String("template-directory", "/usr/local/rct/server/templates", "Path to the folder storing RCT server templates (this file -> server/templates)")
staticDirectory := flag.String("static-directory", "/usr/local/rct/server/static", "Path to the folder storing RCT server templates (this file -> server/static)")
flag.Parse()
if len(flag.Args()) > 0 {
log.Fatalf("Usage: server [-directory DIRECTORY] ")
}
h := new(RegexpHandler)
renderRoute, err := regexp.Compile("/experiments/.*/iterations/.+/.+/render")
if err != nil {
log.Fatal(err)
}
iterationRoute, err := regexp.Compile("/experiments/.*/iterations/.+/.+")
if err != nil {
log.Fatal(err)
}
staticRoute, err := regexp.Compile("/static")
if err != nil {
log.Fatal(err)
}
defaultRoute, err := regexp.Compile("/")
if err != nil {
log.Fatal(err)
}
h.HandleFunc(renderRoute, renderHandler(*directory, *templateDirectory))
h.HandleFunc(iterationRoute, newRctHandler(*directory, *templateDirectory))
h.Handler(staticRoute, http.StripPrefix("/static", http.FileServer(http.Dir(*staticDirectory))))
h.Handler(defaultRoute, http.FileServer(http.Dir(*directory)))
allHandlers := jsonStripper(serverHeaderHandler(h))
log.Fatal(http.ListenAndServe(":8080", handlers.LoggingHandler(os.Stdout, allHandlers)))
}
开发者ID:silky,项目名称:rct,代码行数:33,代码来源:main.go
示例14: StartWebServer
func StartWebServer() error {
conf, err := config.GetConfig()
if err != nil {
return err
}
var hystrixTimeout time.Duration
conf.Hystrix.Timeout = strings.TrimSpace(conf.Hystrix.Timeout)
if conf.Hystrix.Timeout != "" {
hystrixTimeout, err = time.ParseDuration(conf.Hystrix.Timeout)
if err != nil || hystrixTimeout < time.Millisecond {
hystrixTimeout = time.Second
log15.Error("Use default time", "module", "hystrix", "timeout", hystrixTimeout)
}
}
hystrix.ConfigureCommand("waitFor", hystrix.CommandConfig{
Timeout: int(int64(hystrixTimeout) / int64(time.Millisecond)), // converted into Millisecond.
MaxConcurrentRequests: conf.Hystrix.MaxConcurrentRequests,
ErrorPercentThreshold: conf.Hystrix.ErrorPercentThreshold,
RequestVolumeThreshold: conf.Hystrix.RequestVolumeThreshold,
SleepWindow: conf.Hystrix.SleepWindow,
})
e := echo.New()
e.Post("/api/v1/tweet", createTweetV1)
e.Get("/api/v1/tweets/:id", getAllTweetForV1)
e.Get("/api/v1/wait/:timeout", waitFor)
e.Get("/api/v1/wait_protected/:timeout", waitForProtected)
e.Static("/", "www/static/")
logsrv := log15.New("pid", os.Getpid(), "addr", conf.Web.Address)
return listenAndServer(logsrv, conf.Web.Address, handlers.LoggingHandler(os.Stdout, handlers.CompressHandler(e.Router())))
}
开发者ID:jerome-laforge,项目名称:mytweeter,代码行数:33,代码来源:webwserver.go
示例15: main
func main() {
flag.Usage = usage
flag.Parse()
args := flag.Args()
if len(args) != 3 {
usage()
return
}
if gpgpubkey == nil {
fmt.Fprintf(os.Stderr, "internal error: gpgpubkey is nil")
return
}
if https == nil {
fmt.Fprintf(os.Stderr, "internal error: https is nil")
return
}
if port == nil {
fmt.Fprintf(os.Stderr, "internal error: port is nil")
return
}
directory = args[0]
username = args[1]
password = args[2]
os.RemoveAll(path.Join(directory, "tmp"))
err := os.MkdirAll(path.Join(directory, "tmp"), 0755)
if err != nil {
fmt.Fprintf(os.Stderr, "%v", err)
return
}
uploads = make(map[int]*upload)
authHandler := func(h http.HandlerFunc) http.Handler {
return authBasic(username, password, h)
}
r := mux.NewRouter()
r.HandleFunc("/", renderListOfACIs)
r.HandleFunc("/pubkeys.gpg", getPubkeys)
r.Handle("/{image}/startupload", authHandler(initiateUpload))
r.Handle("/manifest/{num}", authHandler(uploadManifest))
r.Handle("/signature/{num}", authHandler(receiveUpload(tmpSigPath, gotSig)))
r.Handle("/aci/{num}", authHandler(receiveUpload(tmpACIPath, gotACI)))
r.Handle("/complete/{num}", authHandler(completeUpload))
r.HandleFunc("/find", find)
r.NotFoundHandler = http.FileServer(http.Dir(directory))
h := handlers.LoggingHandler(os.Stderr, r)
addr := ":" + strconv.Itoa(*port)
log.Println("Listening on", addr)
log.Fatal(http.ListenAndServe(addr, h))
}
开发者ID:appc,项目名称:acserver,代码行数:60,代码来源:main.go
示例16: FilteredLoggingHandler
func FilteredLoggingHandler(filteredPaths map[string]struct{}, writer io.Writer, router http.Handler) http.Handler {
return filteredLoggingHandler{
filteredPaths: filteredPaths,
handler: router,
loggingHandler: handlers.LoggingHandler(writer, router),
}
}
开发者ID:th3architect,项目名称:longhorn,代码行数:7,代码来源:util.go
示例17: main
func main() {
webroot := "/var/www"
bind := "localhost:8000"
flag.StringVar(&webroot, "webroot", "/var/www", "web application root")
flag.StringVar(&bind, "bind", "localhost:8000", "<host>:<port> or just <host> or <port>")
flag.Parse()
log.Println("")
log.Println(" `( ◔ ౪◔)´")
log.Println("")
log.Println(" Server running on :8000")
r := mux.NewRouter()
r.HandleFunc("/ping", PingHandler)
r.HandleFunc("/settings", SettingsHandler)
r.HandleFunc("/test/lastfm", testArtistSearch)
r.PathPrefix("/").Handler(
handlers.LoggingHandler(os.Stdout,
http.FileServer(http.Dir(webroot))))
//r.HandleFunc("/socket.io", SocketHandler)
err := http.ListenAndServe(bind, r)
if err != nil {
panic(err)
}
}
开发者ID:rohanpandula,项目名称:cans,代码行数:27,代码来源:main.go
示例18: main
func main() {
//start a db session
session, err := mgo.Dial("localhost")
if err != nil {
fmt.Println(err)
return //UGLY HACK: there are "too many" errors here.
}
ctx := appContext{db: session, decoder: schema.NewDecoder()} //db, templates map, decoder
loggedRouter := handlers.LoggingHandler(os.Stdout, http.DefaultServeMux)
fs := handlers.LoggingHandler(os.Stdout, http.FileServer(http.Dir("assets")))
http.Handle("/", fs)
http.HandleFunc("/submit", ctx.receiveSubmission )
http.HandleFunc("/unlock/", ctx.unlockHandler)
log.Fatal(http.ListenAndServe(":3000", loggedRouter))
}
开发者ID:rm8x,项目名称:golang-demoserver,代码行数:16,代码来源:demoserver.go
示例19: 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
示例20: RunAPI
func RunAPI() {
r := mux.NewRouter()
r.HandleFunc("/groups", func(w http.ResponseWriter, r *http.Request) {
group_server.HandleCreate(w, r)
}).Methods("POST")
r.HandleFunc("/groups/{gid}", func(w http.ResponseWriter, r *http.Request) {
group_server.HandleDisband(w, r)
}).Methods("DELETE")
r.HandleFunc("/groups/{gid}/members", func(w http.ResponseWriter, r *http.Request) {
group_server.HandleAddGroupMember(w, r)
}).Methods("POST")
r.HandleFunc("/groups/{gid}/members/{mid}", func(w http.ResponseWriter, r *http.Request) {
group_server.HandleQuitGroup(w, r)
}).Methods("DELETE")
r.HandleFunc("/device/bind", BindToken).Methods("POST")
r.HandleFunc("/device/unbind", UnbindToken).Methods("POST")
r.HandleFunc("/notification/groups/{gid}", SetGroupQuiet).Methods("POST")
r.HandleFunc("/auth/grant", AuthGrant).Methods("POST")
r.HandleFunc("/messages", PostIMMessage).Methods("POST")
r.HandleFunc("/messages", LoadLatestMessage).Methods("GET")
http.Handle("/", handlers.LoggingHandler(os.Stdout, r))
var PORT = config.port
var BIND_ADDR = ""
addr := fmt.Sprintf("%s:%d", BIND_ADDR, PORT)
SingleHTTPService(addr, nil)
}
开发者ID:karlom,项目名称:im_service,代码行数:32,代码来源:api.go
注:本文中的github.com/gorilla/handlers.LoggingHandler函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论