Created
October 19, 2015 21:44
-
-
Save kentquirk/7690a3e6637007d4944b to your computer and use it in GitHub Desktop.
compose handlers in go
This file contains hidden or 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
// CountRequests is middleware for standard handler functions | |
func (vc *VascoClient) CountRequests(handler http.HandlerFunc) http.HandlerFunc { | |
return func(rw http.ResponseWriter, req *http.Request) { | |
// we use a recorder as our response writer so we can inspect it | |
recorder := httptest.NewRecorder() | |
// now call the original handler with our recorder | |
handler(recorder, req) | |
// switch on the result | |
code := recorder.Code | |
switch { | |
case code >= 400 && code <= 499: | |
vc.CountUserError() | |
case code >= 500 && code <= 599: | |
vc.CountServerError() | |
default: | |
} | |
vc.CountQuery() | |
// and now play back the stuff that the handler set | |
for k, v := range recorder.Header() { | |
rw.Header()[k] = v | |
} | |
rw.WriteHeader(recorder.Code) | |
rw.Write(recorder.Body.Bytes()) | |
} | |
} | |
// LogRequests is middleware | |
func (vc *VascoClient) LogRequests(handler http.HandlerFunc) http.HandlerFunc { | |
return func(rw http.ResponseWriter, req *http.Request) { | |
log.Printf("%s %s\n", req.Method, req.URL) | |
handler(rw, req) | |
} | |
} | |
// CL is middleware that composes LogRequests and CountRequests | |
func (vc *VascoClient) CL(handler http.HandlerFunc) http.HandlerFunc { | |
return vc.LogRequests(vc.CountRequests(handler)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment