Skip to content
This repository has been archived by the owner on May 8, 2023. It is now read-only.

Commit

Permalink
Add http timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
roy2100 committed Jun 3, 2022
1 parent 6c06689 commit 566482a
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
11 changes: 9 additions & 2 deletions pkg/weibo/download.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package weibo

import (
"context"
"fmt"
"io"
"io/ioutil"
Expand Down Expand Up @@ -87,18 +88,24 @@ func (w *Weibo) downloadPics(pics []string, distDir string) error {
go func(p string) (err error) {
c <- struct{}{}
defer func() {
wg.Done()
if pErr := recover(); pErr != nil {
err = fmt.Errorf("panic: err: %v", pErr)
}
if err != nil {
lastErr = err
}
<-c
wg.Done()
}()

// 防止频控
ran := rand.Int31n(100)
time.Sleep(time.Duration(ran) * time.Millisecond)

req, err := http.NewRequest("GET", p, nil)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()

req, err := http.NewRequestWithContext(ctx, "GET", p, nil)
if err != nil {
return err
}
Expand Down
4 changes: 3 additions & 1 deletion pkg/weibo/download_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package weibo

import "testing"
import (
"testing"
)

func TestDownLoadShowPics(t *testing.T) {
w := Weibo{}
Expand Down

0 comments on commit 566482a

Please sign in to comment.