add SetBodyContent for gclient.Response

This commit is contained in:
John Guo
2022-06-17 11:31:32 +08:00
parent cbf5ee9649
commit cf5884bc60
2 changed files with 32 additions and 0 deletions

View File

@ -7,6 +7,7 @@
package gclient
import (
"bytes"
"io/ioutil"
"net/http"
@ -69,6 +70,13 @@ func (r *Response) ReadAllString() string {
return string(r.ReadAll())
}
// SetBodyContent overwrites response content with custom one.
func (r *Response) SetBodyContent(content []byte) {
buffer := bytes.NewBuffer(content)
r.Body = ioutil.NopCloser(buffer)
r.ContentLength = int64(buffer.Len())
}
// Close closes the response when it will never be used.
func (r *Response) Close() error {
if r == nil || r.Response == nil {

View File

@ -640,3 +640,27 @@ func TestClient_RequestVar(t *testing.T) {
t.AssertNE(users, nil)
})
}
func TestClient_SetBodyContent(t *testing.T) {
p, _ := gtcp.GetFreePort()
s := g.Server(p)
s.BindHandler("/", func(r *ghttp.Request) {
r.Response.Write("hello")
})
s.SetPort(p)
s.SetDumpRouterMap(false)
s.Start()
defer s.Shutdown()
time.Sleep(100 * time.Millisecond)
gtest.C(t, func(t *gtest.T) {
c := g.Client()
c.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
res, err := c.Get(ctx, "/")
t.AssertNil(err)
defer res.Close()
t.Assert(res.ReadAllString(), "hello")
res.SetBodyContent([]byte("world"))
t.Assert(res.ReadAllString(), "world")
})
}