mirror of
https://github.com/optim-enterprises-bv/vault.git
synced 2025-11-03 03:58:01 +00:00
api: Allow reseting of request body
This commit is contained in:
@@ -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))
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user