You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
1.4 KiB
Go

package main
import (
"fmt"
"net/http"
)
// recoverPanic provides middleware for recovering from panics in the same goroutine that
// executred the recoverPanic middleware.
//
// This means that panics from goroutines created in handler operations will still need
// to be handled separately.Failure to do so will cause the application to exit and bring
// down the server.
func (app *application) recoverPanic(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Create a deferred function (which will always be run in the event of a panic
// as Go unwinds the stack).
defer func() {
if err := recover(); err != nil {
// If there was a panic, set a "Connection: close" header on the
// response. This acts as a trigger to make Go's HTTP server
// automatically close the current connection after a response has been
// sent.
w.Header().Set("Connection", "close")
app.serverErrorResponse(w, r, fmt.Errorf("%s", http.ErrAbortHandler))
}
}()
next.ServeHTTP(w, r)
})
}
func (app *application) RquestLoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var (
ip = r.RemoteAddr
proto = r.Proto
method = r.Method
uri = r.URL.RequestURI()
)
app.logger.Info("recieved request", "ip", ip, "proto", proto, "method", method, "uri", uri)
next.ServeHTTP(w, r)
})
}