Skip to content

Commit

Permalink
上传进度条功能
Browse files Browse the repository at this point in the history
  • Loading branch information
guonaihong committed Jul 21, 2020
1 parent c73a5f4 commit b0e10ec
Show file tree
Hide file tree
Showing 3 changed files with 102 additions and 0 deletions.
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,21 @@ func main() {
gout.POST(":6666/compress").RequestUse(request.GzipDecompress()).SetBody(buf).Do()
}
```
### upload 进度条
```go
package main

import (
"bytes"
"github.com/antlabs/gout-middleware/request"
"github.com/guonaihong/gout"
)

func main() {
gout.POST(":8080").RequestUse(request.ProgressBar(func(currBytes, totalBytes int) {

fmt.Printf("%d:%d-->%f%%\n", currBytes, totalBytes, float64(currBytes)/float64(totalBytes))
})).SetBody(strings.Repeat("1", 100000) /*构造大点的测试数据,这里换成真实业务数据*/).Do()
}

```
38 changes: 38 additions & 0 deletions request/progress_bar.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package request

import (
"io"
"io/ioutil"
"net/http"

api "github.com/guonaihong/gout/interface"
)

//上传进度条
type progressBar struct {
callback func(currBytes, totalBytes int)
r io.Reader
currBytes int
totalBytes int
}

func (g *progressBar) Read(p []byte) (n int, err error) {
n, err = g.r.Read(p)
g.currBytes += n
if n > 0 && g.callback != nil {
g.callback(g.currBytes, g.totalBytes)
}

return
}

func (g *progressBar) ModifyRequest(req *http.Request) error {
g.r = req.Body
req.Body = ioutil.NopCloser(g)
g.totalBytes = int(req.ContentLength)
return nil
}

func ProgressBar(callback func(currBytes, totalBytes int)) api.RequestMiddler {
return &progressBar{callback: callback}
}
46 changes: 46 additions & 0 deletions request/progress_bar_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package request

import (
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"

"github.com/gin-gonic/gin"
"github.com/guonaihong/gout"
"github.com/stretchr/testify/assert"
)

type readWait struct {
r io.Reader
}

func (r *readWait) Read(p []byte) (n int, err error) {
n, err = r.r.Read(p[:512])
return
}

func createProgressBarServer() *httptest.Server {
r := gin.New()
r.POST("/", func(c *gin.Context) {
r := &readWait{r: c.Request.Body}
_, _ = ioutil.ReadAll(r)

c.String(200, "hello")
})

return httptest.NewServer(http.HandlerFunc(r.ServeHTTP))
}

func TestProgressBar(t *testing.T) {
ts := createProgressBarServer()
call := false
gout.POST(ts.URL).RequestUse(ProgressBar(func(currBytes, totalBytes int) {
call = true
//fmt.Printf("%d:%d\n", currBytes, totalBytes)
})).SetBody(strings.Repeat("1", 100000)).Do()

assert.True(t, call)
}

0 comments on commit b0e10ec

Please sign in to comment.