Skip to content

Commit

Permalink
feat: support pipe function for stream
Browse files Browse the repository at this point in the history
  • Loading branch information
vicanso committed Jun 8, 2019
1 parent c035e10 commit 5bc54ab
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -821,6 +821,18 @@ c := cod.NewContext(resp, req)
c.DisableReuse()
```

### Pipe

将当前Reader pipe向Response,用于流式输出响应数据,节省内存。

```go
resp := httptest.NewRecorder()
c := NewContext(resp, nil)
data := []byte("abcd")
r := bytes.NewReader(data)
c.Pipe(r)
```

## Group

### NewGroup
Expand Down
7 changes: 7 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package cod
import (
"bytes"
"fmt"
"io"
"mime"
"net"
"net/http"
Expand Down Expand Up @@ -436,6 +437,12 @@ func (c *Context) Pass(another *Cod) {
another.ServeHTTP(c.Response, c.Request)
}

// Pipe pie to the response
func (c *Context) Pipe(r io.Reader) (written int64, err error) {
c.Committed = true
return io.Copy(c.Response, r)
}

// NewContext new a context
func NewContext(resp http.ResponseWriter, req *http.Request) *Context {
c := &Context{}
Expand Down
13 changes: 13 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -466,10 +466,23 @@ func TestContextPass(t *testing.T) {
resp := httptest.NewRecorder()
d.GET("/", func(c *Context) error {
c.Pass(another)
// the data will be ignored
c.BodyBuffer = bytes.NewBufferString("original data")
return nil
})
d.ServeHTTP(resp, req)
assert.Equal(resp.Code, 200)
assert.Equal(resp.Body.String(), "new data")
}

func TestPipe(t *testing.T) {
assert := assert.New(t)
resp := httptest.NewRecorder()
c := NewContext(resp, nil)
data := []byte("abcd")
r := bytes.NewReader(data)
written, err := c.Pipe(r)
assert.Nil(err)
assert.Equal(written, int64(len(data)))
assert.Equal(data, resp.Body.Bytes())
}

0 comments on commit 5bc54ab

Please sign in to comment.