mirror of
https://gitee.com/johng/gf
synced 2026-06-06 02:25:47 +08:00
add SetBodyContent for gclient.Response
This commit is contained in:
@ -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 {
|
||||
|
||||
@ -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")
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user