Last active
December 31, 2019 11:21
-
-
Save kyktommy/f90d345ad3b1cdb8cb76d06e14b6d36e to your computer and use it in GitHub Desktop.
httplog.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
package main | |
import ( | |
"bytes" | |
"fmt" | |
"io" | |
"io/ioutil" | |
"net/http" | |
"strings" | |
) | |
type bodyLogWriter struct { | |
http.ResponseWriter | |
body *bytes.Buffer | |
} | |
func (w bodyLogWriter) Write(b []byte) (int, error) { | |
w.body.Write(b) | |
return w.ResponseWriter.Write(b) | |
} | |
func main() { | |
httpLog := func(next http.Handler) http.Handler { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
// copy buffer from request | |
var sb bytes.Buffer | |
io.Copy(&sb, r.Body) | |
// assign back to request body | |
r.Body = ioutil.NopCloser(strings.NewReader(sb.String())) | |
// create logger writer | |
blw := &bodyLogWriter{ | |
body: bytes.NewBufferString(""), | |
ResponseWriter: w, | |
} | |
// call next route | |
next.ServeHTTP(blw, r) | |
// print out | |
fmt.Printf("url: %s\nrequest params: %s \nresponse data: %s\n\n", r.URL, sb.String(), blw.body.String()) | |
}) | |
} | |
// route return what body has | |
route := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
var sb bytes.Buffer | |
io.Copy(&sb, r.Body) | |
w.Header().Set("hello", "world") | |
w.Write(sb.Bytes()) | |
}) | |
http.Handle("/foo", httpLog(route)) | |
http.ListenAndServe(":8080", nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment