forked from gohiweeds/twitterdownloader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
75 lines (61 loc) · 1.33 KB
/
client.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package twitterdownloader
import (
"errors"
"io/ioutil"
"net/http"
"os"
"strings"
)
type Client struct {
client *http.Client
proxyType int
proxyUrl string
socks5Proto string
socks5IpPort string
}
/// Init client structure
func NewClient() *Client {
return &Client{
client: &http.Client{},
}
}
func (c Client) Get(url string) error {
if c.client == nil {
c.client = &http.Client{}
}
resp, err := c.client.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
fileName := extractFilename(url)
body, err := ioutil.ReadAll(resp.Body)
if err = ioutil.WriteFile(fileName, body, os.ModePerm); err != nil {
return err
}
return nil
}
func (c *Client) GetWithProxy(url string) (string, error) {
if c.client == nil {
return "", errors.New("Client is nil, should init with proxy")
}
resp, err := c.client.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
fileName := extractFilename(url)
fileName = strings.Split(fileName, ":")[0]
body, err := ioutil.ReadAll(resp.Body)
if err = ioutil.WriteFile(fileName, body, os.ModePerm); err != nil {
return "", err
}
return fileName, nil
}
func extractFilename(url string) string {
strs := strings.Split(url, "/")
fileName := strs[len(strs)-1]
params := strings.Split(fileName, "&")
param := params[len(params)-1]
return param
}