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