Commit 59b1e8b0 authored by Carter's avatar Carter

Now logging the request body

Logging the request body if the Content-Type is application/json or
application/xml
parent dbd76f7a
package httpserver
import (
"io/ioutil"
"log"
"net"
"net/http"
"net/http/httputil"
......@@ -119,6 +121,19 @@ func NewReplacer(r *http.Request, rr *ResponseRecorder, emptyValue string) Repla
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,
}
......@@ -132,6 +147,19 @@ func NewReplacer(r *http.Request, rr *ResponseRecorder, emptyValue string) Repla
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
// the string with the replaced values.
func (r *replacer) Replace(s string) string {
......@@ -226,6 +254,9 @@ func (r *replacer) Set(key, value string) {
}
const (
timeFormat = "02/Jan/2006:15:04:05 -0700"
headerReplacer = "{>"
timeFormat = "02/Jan/2006:15:04:05 -0700"
headerReplacer = "{>"
headerContentType = "Content-Type"
contentTypeJSON = "application/json"
contentTypeXML = "application/xml"
)
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment