-
-
Save kevburnsjr/2080536ba62a7f111ec9d11bd950f113 to your computer and use it in GitHub Desktop.
A simpler http midleware implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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