mirror of
https://github.com/caddyserver/caddy.git
synced 2024-11-26 02:09:47 +08:00
refactor and added test
This commit is contained in:
parent
d06c15cae6
commit
3fd8218f67
|
@ -127,12 +127,9 @@ func NewReplacer(r *http.Request, rr *ResponseRecorder, emptyValue string) Repla
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
body, err := ioutil.ReadAll(r.Body)
|
body, err := readRequestBody(r)
|
||||||
// Create a new ReadCloser to keep the body from being drained.
|
|
||||||
r.Body = ioutil.NopCloser(bytes.NewBuffer(body))
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("[WARNING] Cannot read request body %v", err)
|
log.Printf("[WARNING] Cannot copy request body %v", err)
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -164,6 +161,18 @@ func canLogRequest(r *http.Request) (canLog bool) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// readRequestBody reads the request body and sets a
|
||||||
|
// new io.ReadCloser that has not yet been read.
|
||||||
|
func readRequestBody(r *http.Request) ([]byte, error) {
|
||||||
|
body, err := ioutil.ReadAll(r.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// Create a new ReadCloser to keep the body from being drained.
|
||||||
|
r.Body = ioutil.NopCloser(bytes.NewBuffer(body))
|
||||||
|
return body, nil
|
||||||
|
}
|
||||||
|
|
||||||
// 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 {
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
package httpserver
|
package httpserver
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"os"
|
"os"
|
||||||
|
@ -161,3 +162,25 @@ func TestRound(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestReadRequestBody(t *testing.T) {
|
||||||
|
r, err := http.NewRequest("POST", "/", strings.NewReader(`null`))
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
defer r.Body.Close()
|
||||||
|
|
||||||
|
body, err := readRequestBody(r)
|
||||||
|
if err != nil {
|
||||||
|
t.Error("readRequestBody failed", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var data = make([]byte, len(body))
|
||||||
|
_, err = r.Body.Read(data)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
} else if !bytes.Equal(body, data) {
|
||||||
|
t.Error("Expceted equal bytes.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue
Block a user