Skip to content

Commit

Permalink
Feat(resp): add ResponseBody func to acquire resp body (#356)
Browse files Browse the repository at this point in the history
* Feat(resp): add ResponseBody func to acquire resp body in middlewares

* add optional field to descide whether wrap the resp body

Co-authored-by: whalecold <zhenglisheng@caicloud.io>
  • Loading branch information
whalecold and whalecold committed Sep 21, 2020
1 parent 798a18a commit dcb2879
Showing 1 changed file with 24 additions and 4 deletions.
28 changes: 24 additions & 4 deletions service/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,13 +170,19 @@ type ResponseWriter interface {
StatusCode() int
// ContentLength returns the length of written content.
ContentLength() int
// ResponseBody returns response body.
ResponseBody() []byte
// SetWrapRespBodyPolicy set wrap resp body policy.
SetWrapRespBodyPolicy(bool)
}

type response struct {
writer http.ResponseWriter
statusCode int
contentLength int
hijacked bool
writer http.ResponseWriter
statusCode int
contentLength int
hijacked bool
ifWrapRespBody bool
respBody []byte
}

// For http.HTTPResponseWriter and HTTPResponseInfo
Expand All @@ -191,6 +197,10 @@ func (c *response) Write(data []byte) (int, error) {
}
length, err := c.writer.Write(data)
c.contentLength += length
// Append the data to the response cache for the special purpose of users.
if c.ifWrapRespBody {
c.respBody = append(c.respBody, data[:length]...)
}
return length, err
}

Expand Down Expand Up @@ -241,6 +251,16 @@ func (c *response) HeaderWritable() bool {
return !c.hijacked && c.statusCode <= 0
}

// ResponseBody returns response body.
func (c *response) ResponseBody() []byte {
return c.respBody
}

// SetWrapRespBodyPolicy set wrap resp body policy.
func (c *response) SetWrapRespBodyPolicy(v bool) {
c.ifWrapRespBody = v
}

// HTTPContext describes an http context.
type HTTPContext interface {
Request() *http.Request
Expand Down

0 comments on commit dcb2879

Please sign in to comment.