Commit 0454e1f4 authored by Armon Dadgar's avatar Armon Dadgar
Browse files

api: Allow reseting of request body

parent 4574b7e0
No related merge requests found
Showing with 42 additions and 0 deletions
+42 -0
......@@ -14,6 +14,7 @@ type Request struct {
Method string
URL *url.URL
Params url.Values
Obj interface{}
Body io.Reader
BodySize int64
}
......@@ -26,11 +27,20 @@ func (r *Request) SetJSONBody(val interface{}) error {
return err
}
r.Obj = val
r.Body = buf
r.BodySize = int64(buf.Len())
return nil
}
// ResetJSONBody is used to reset the body for a redirect
func (r *Request) ResetJSONBody() error {
if r.Body == nil {
return nil
}
return r.SetJSONBody(r.Obj)
}
// ToHTTP turns this request into a valid *http.Request for use with the
// net/http package.
func (r *Request) ToHTTP() (*http.Request, error) {
......
......@@ -29,3 +29,35 @@ func TestRequestSetJSONBody(t *testing.T) {
t.Fatalf("bad: %d", len(actual))
}
}
func TestRequestResetJSONBody(t *testing.T) {
var r Request
raw := map[string]interface{}{"foo": "bar"}
if err := r.SetJSONBody(raw); err != nil {
t.Fatalf("err: %s", err)
}
var buf bytes.Buffer
if _, err := io.Copy(&buf, r.Body); err != nil {
t.Fatalf("err: %s", err)
}
if err := r.ResetJSONBody(); err != nil {
t.Fatalf("err: %s", err)
}
var buf2 bytes.Buffer
if _, err := io.Copy(&buf2, r.Body); err != nil {
t.Fatalf("err: %s", err)
}
expected := `{"foo":"bar"}`
actual := strings.TrimSpace(buf2.String())
if actual != expected {
t.Fatalf("bad: %s", actual)
}
if int64(len(buf2.String())) != r.BodySize {
t.Fatalf("bad: %d", len(actual))
}
}
Supports Markdown
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