Now logging the request body

Logging the request body if the Content-Type is application/json or
application/xml
This commit is contained in:
Carter 2016-08-10 10:04:57 -04:00
parent dbd76f7a57
commit 59b1e8b0bc

View File

@ -1,6 +1,8 @@
package httpserver package httpserver
import ( import (
"io/ioutil"
"log"
"net" "net"
"net/http" "net/http"
"net/http/httputil" "net/http/httputil"
@ -119,6 +121,19 @@ func NewReplacer(r *http.Request, rr *ResponseRecorder, emptyValue string) Repla
return requestReplacer.Replace(string(dump)) return requestReplacer.Replace(string(dump))
}, },
"{request_body}": func() string {
if !canLogRequest(r) {
return ""
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Printf("[WARNING] Cannot read request body %v", err)
return ""
}
return string(body)
},
}, },
emptyValue: emptyValue, emptyValue: emptyValue,
} }
@ -132,6 +147,19 @@ func NewReplacer(r *http.Request, rr *ResponseRecorder, emptyValue string) Repla
return rep return rep
} }
func canLogRequest(r *http.Request) (canLog bool) {
if r.Method == "POST" || r.Method == "PUT" {
for _, cType := range r.Header[headerContentType] {
// the cType could have charset and other info
if strings.Index(cType, contentTypeJSON) > -1 || strings.Index(cType, contentTypeXML) > -1 {
canLog = true
break
}
}
}
return
}
// Replace performs a replacement of values on s and returns // Replace performs a replacement of values on s and returns
// the string with the replaced values. // the string with the replaced values.
func (r *replacer) Replace(s string) string { func (r *replacer) Replace(s string) string {
@ -228,4 +256,7 @@ func (r *replacer) Set(key, value string) {
const ( const (
timeFormat = "02/Jan/2006:15:04:05 -0700" timeFormat = "02/Jan/2006:15:04:05 -0700"
headerReplacer = "{>" headerReplacer = "{>"
headerContentType = "Content-Type"
contentTypeJSON = "application/json"
contentTypeXML = "application/xml"
) )