-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfileio.go
69 lines (62 loc) · 1.45 KB
/
fileio.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
package fileio
import (
"bytes"
"mime/multipart"
"os"
"fmt"
"io"
"log"
"net/http"
"io/ioutil"
)
type FileIoResult struct {
Success bool
Key string
Link string
Expiry string
}
func createMultipartFormData(fieldName, fileName string) (bytes.Buffer, *multipart.Writer) {
var b bytes.Buffer
var err error
w := multipart.NewWriter(&b)
var fw io.Writer
file := mustOpen(fileName)
if fw, err = w.CreateFormFile(fieldName, file.Name()); err != nil {
fmt.Println("Error building form file")
}
if _, err = io.Copy(fw, file); err != nil {
fmt.Println("Error with io.copy")
}
w.Close()
return b, w
}
func SendFile(filePath string) (string, int){
b,w := createMultipartFormData("file",filePath)
req, err := http.NewRequest("POST", "http://file.io", &b)
if err != nil {
return "none",0
}
client := &http.Client{}
req.Header.Set("Content-Type", w.FormDataContentType())
resp, _ := client.Do(req)
if resp.StatusCode != 200{
return "",resp.StatusCode
}else{
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
bodyString := string(bodyBytes)
fmt.Println(bodyString)
return bodyString,resp.StatusCode;
}
}
func mustOpen(f string) *os.File {
r, err := os.Open(f)
if err != nil {
pwd, _ := os.Getwd()
fmt.Println("PWD: ", pwd)
fmt.Println("The file specified can't be found.")
}
return r
}