Skip to content

Instantly share code, notes, and snippets.

@Hypro999
Created June 24, 2021 16:37
Show Gist options
  • Save Hypro999/d347b142e63575ae84d6c7c20b2ac068 to your computer and use it in GitHub Desktop.
Save Hypro999/d347b142e63575ae84d6c7c20b2ac068 to your computer and use it in GitHub Desktop.
A simple demonstration of how to write middleware for HTTP handlers in Go.
package main
import (
"log"
"net/http"
)
var (
GREETING = []byte("Hello there!")
)
func Logger(handler http.Handler) http.Handler {
var wrappedHandler http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
// Before:
log.Printf("Request to %s initiated", r.URL.Path)
// Call inner handler (what we are wrapping):
handler.ServeHTTP(w, r)
//After:
log.Printf("Request to %s completed", r.URL.Path)
}
return wrappedHandler
}
func Greet(w http.ResponseWriter, r *http.Request) {
w.Write(GREETING)
}
func main() {
http.Handle("/", Logger(http.HandlerFunc(Greet)))
log.Fatalln(http.ListenAndServe(":8000", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment