forked from javahongxi/golab
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfetcher.go
59 lines (49 loc) · 1.11 KB
/
fetcher.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package fetcher
import (
"bufio"
"fmt"
"io/ioutil"
"net/http"
"log"
"time"
"github.com/javahongxi/golab/crawler/config"
"golang.org/x/net/html/charset"
"golang.org/x/text/encoding"
"golang.org/x/text/encoding/unicode"
"golang.org/x/text/transform"
)
var (
rateLimiter = time.Tick(time.Second / config.Qps)
verboseLogging = false
)
func SetVerboseLogging() {
verboseLogging = true
}
func Fetch(url string) ([]byte, error) {
<-rateLimiter
if verboseLogging {
log.Printf("Fetching url %s", url)
}
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("wrong status code: %d", resp.StatusCode)
}
bodyReader := bufio.NewReader(resp.Body)
e := determineEncoding(bodyReader)
utf8Reader := transform.NewReader(bodyReader, e.NewDecoder())
return ioutil.ReadAll(utf8Reader)
}
func determineEncoding(
r *bufio.Reader) encoding.Encoding {
bytes, err := r.Peek(1024)
if err != nil {
log.Printf("Fetcher error: %v", err)
return unicode.UTF8
}
e, _, _ := charset.DetermineEncoding(bytes, "")
return e
}