Skip to content

Instantly share code, notes, and snippets.

@kevburnsjr
Created August 22, 2017 17:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevburnsjr/2080536ba62a7f111ec9d11bd950f113 to your computer and use it in GitHub Desktop.
Save kevburnsjr/2080536ba62a7f111ec9d11bd950f113 to your computer and use it in GitHub Desktop.
A simpler http midleware implementation
package main
import (
"net/http"
"time"
"log"
)
func main() {
var h http.Handler = http.HandlerFunc(Router)
h = Timer(h)
h = DontCache(h)
http.ListenAndServe(":80", h)
}
// Middleware
func DontCache(next http.Handler) http.Handler {
return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Cache-Control", "max-age=0, no-cache, must-revalidate")
next.ServeHTTP(res, req)
})
}
func Timer(next http.Handler) http.Handler {
return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
start := time.Now()
next.ServeHTTP(res, req)
log.Printf("%d %s", time.Since(start).Nanoseconds() / 1e3, req.URL.Path)
})
}
// Router
var routes = map[string]func(http.ResponseWriter, *http.Request){
"/": IndexHandler,
"/hello": HelloHandler,
"/world": WorldHandler,
"/panic": PanicHandler,
}
func Router(w http.ResponseWriter, r *http.Request) {
if handle, ok := routes[r.URL.Path]; ok {
handle(w, r)
} else {
http.Error(w, "Not Found : "+r.URL.Path, 404)
}
}
func IndexHandler(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Hello, World!", 200)
}
func HelloHandler(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Hello", 200)
}
func WorldHandler(w http.ResponseWriter, r *http.Request) {
http.Error(w, "World", 200)
}
func PanicHandler(w http.ResponseWriter, r *http.Request) {
log.Panic("REM WAS RIGHT")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment