This document discusses writing HTTP middleware in Go. It begins by introducing HTTP middleware and how it can wrap HTTP handlers to execute logic before and after handlers. It then demonstrates how to write middleware that logs requests, and how middleware can be chained together. Finally, it shows how to use the Negroni package to write middleware and apply middleware to specific routes.
3. HTTP Handlers
!
!
!
!
!
!
Handlers are responsible for writing headers and bodies !
into HTTP responses. !
!
// ServeHTTP should write reply headers and data
// to the ResponseWriter and then return.
!
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
4. HTTP Middleware
• Pluggable and self-contained piece of code that
wraps web application handlers.!
• Components that work as another layer in the
request handling cycle, which can execute some
logic before or after executing your HTTP
application handlers.!
• Great for implementing cross-cutting concerns:
Authentication, authorization, caching, logging,
etc.
!
5. Using StripPrefix to Wraps http.FileServer
handler
package main
!
import (
"net/http"
)
!
func main() {
// To serve a directory on disk under an alternate URL
// path (/public/), use StripPrefix to modify the request
// URL's path before the FileServer sees it:
!
fs := http.FileServer(http.Dir("public"))
http.Handle("/public/", http.StripPrefix("/public/", fs))
}
14. Writing HTTP Middleware with
Negroni
func MyMiddleware(rw http.ResponseWriter, r *http.Request, next
http.HandlerFunc) {
// logic before executing the next handler
next(rw, r)
// logic after executing the next handler
}
15. Mapping Middleware Chaining
with Negroni
func main() {
mux := http.NewServeMux()
// map your routes here
n := negroni.New()
// You can map it to the handler chain with the Use function:
n.Use(negroni.HandlerFunc(MyMiddleware))
n.UseHandler(mux)
server := &http.Server{
Addr: ":8080",
Handler: n,
}
server.ListenAndServe()
}
16. Register Middleware Handlers for Specific
Routes
router := mux.NewRouter()
adminRoutes := mux.NewRouter()
!
// add admin routes here
.. .
!
// Add route specific Middleware to “/admin” route
router.Handle("/admin", negroni.New(
Middleware1,
Middleware2,
negroni.Wrap(adminRoutes),
))