Repository navigation
Middleware
Thanatat Tamtan edited this page Aug 21, 2018
·
5 revisions
Since hime use net/http handler, you can use net/http middleware style, or any middleware library that work with net/http.
package main
import (
"log"
"net/http"
"github.com/acoshift/hime"
)
func main() {
app := hime.New()
h := logRequest(hime.Handler(index))
err := app.
Handler(h).
Address(":8080").
ListenAndServe()
if err != nil {
log.Fatal(err)
}
}
func index(ctx *hime.Context) error {
return ctx.String("Hello, Hime!!!")
}
func logRequest(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("[%s] %s\n", r.Method, r.RequestURI)
h.ServeHTTP(w, r)
})
}func logRequest(h http.Handler) http.Handler {
return hime.Handler(func(ctx *hime.Context) error {
log.Printf("[%s] %s\n", ctx.Method, ctx.RequestURI)
return ctx.Handle(h)
})
}Using acoshift/middleware
package main
import (
"log"
"net/http"
"github.com/acoshift/hime"
"github.com/acoshift/middleware"
)
func main() {
app := hime.New()
h := middleware.Chain(
panicRecovery,
logRequest,
)(hime.Handler(index))
err := app.
Handler(h).
Address(":8080").
ListenAndServe()
if err != nil {
log.Fatal(err)
}
}
func index(ctx *hime.Context) error {
panic("oh no!!!")
}
func panicRecovery(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
err := recover()
if err != nil {
log.Println(err)
http.Error(w, "Something went wrong D:", http.StatusInternalServerError)
}
}()
h.ServeHTTP(w, r)
})
}
func logRequest(h http.Handler) http.Handler {
return hime.Handler(func(ctx *hime.Context) error {
log.Printf("[%s] %s\n", ctx.Method, ctx.RequestURI)
return ctx.Handle(h)
})
}Using justinas/alice
h := alice.New(
panicRecovery,
logRequest,
).Then(hime.Handler(index))