Created
June 24, 2021 16:37
-
-
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.
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 ( | |
"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