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 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 ...@@ -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 ...@@ -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 {
...@@ -226,6 +254,9 @@ func (r *replacer) Set(key, value string) { ...@@ -226,6 +254,9 @@ 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"
) )
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