-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlif-notifier.go
89 lines (74 loc) · 1.75 KB
/
lif-notifier.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
80
81
82
83
84
85
86
87
88
89
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"time"
)
func OpenFile(file string) (fileContents []byte) {
// Keep trying to read the file until there is not an error
for ok := true; ok == true; ok = true {
fileContents, err := ioutil.ReadFile(file)
if err == nil {
return fileContents
}
log.Println(" ... read file failed (try again in half-a-second): ", err)
time.Sleep(500)
}
return fileContents
}
func Upload(url, file string, key []byte) (err error) {
// Prepare a form that you will submit to that URL.
var b bytes.Buffer
w := multipart.NewWriter(&b)
if err != nil {
return
}
// Filename
fw, err := w.CreateFormField("filename")
if err != nil {
return
}
if _, err = fw.Write([]byte(file)); err != nil {
return
}
// File contents
if fw, err = w.CreateFormField("file"); err != nil {
return
}
if _, err = fw.Write(OpenFile(file)); err != nil {
return
}
// Add the other fields
if fw, err = w.CreateFormField("key"); err != nil {
return
}
if _, err = fw.Write([]byte(key)); err != nil {
return
}
// Don't forget to close the multipart writer.
// If you don't close it, your request will be missing the terminating boundary.
w.Close()
// Now that you have a form, you can submit it to your handler.
req, err := http.NewRequest("POST", url, &b)
if err != nil {
return
}
// Don't forget to set the content type, this will contain the boundary.
req.Header.Set("Content-Type", w.FormDataContentType())
// Submit the request
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
log.Println(" ... upload failed: ", err)
return
}
// Check the response
if res.StatusCode != http.StatusOK {
err = fmt.Errorf("bad status: %s", res.Status)
}
return
}