-
Notifications
You must be signed in to change notification settings - Fork 4
/
upload.go
79 lines (67 loc) · 1.77 KB
/
upload.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
76
77
78
79
package main
import (
"errors"
"io/ioutil"
"path/filepath"
"strings"
"github.com/parnurzeal/gorequest"
)
const uploadUrl string = "https://imgops.com/store"
const uploadSearch string = "userUploadTempCache"
const defaultTarget = "imgops"
var defaultAction bool
var finalUrl string
func setDefaultAction(targetAction string) {
if targetAction != defaultTarget {
defaultAction = false
} else {
defaultAction = true
}
}
func UploadURL(targetUrl string, targetAction string) ([]string, error) {
setDefaultAction(targetAction)
newUrl := "https://imgops.com/" + targetUrl
finalUrl = newUrl
if defaultAction {
return strings.Fields(newUrl), nil
} else {
_, body, errs := gorequest.New().Get(newUrl).End()
if errs != nil {
return strings.Fields(""), errors.New("GET error")
} else {
return findHref(body, targetAction, finalUrl)
}
}
}
func redirectPolicy(req gorequest.Request, via []gorequest.Request) error {
finalUrl = req.URL.String()
if defaultAction {
return errors.New("Stop redirection")
} else {
return nil
}
}
func UploadFile(targetPath string, targetAction string) ([]string, error) {
setDefaultAction(targetAction)
debug("Read file from path")
bytes, _ := ioutil.ReadFile(targetPath)
debug("Make a POST request")
_, body, errs := gorequest.New().
Post(uploadUrl).
RedirectPolicy(redirectPolicy).
Type("multipart").
SendFile(bytes, filepath.Base(targetPath), "photo").
End()
debug("POST request errors: %v", errs)
debug("Final URL: %s", finalUrl)
debug("Stop redirection: %b", defaultAction)
if defaultAction {
if len(finalUrl) > 0 {
return strings.Fields(finalUrl), nil
} else {
return strings.Fields(""), errors.New("Could not get final URL after Redirect")
}
} else {
return findHref(body, targetAction, finalUrl)
}
}