-
Notifications
You must be signed in to change notification settings - Fork 1
/
upload.go
69 lines (66 loc) · 1.56 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
package files
import (
"bytes"
"encoding/hex"
"io"
"log"
"mime/multipart"
"net/http"
"os"
"path/filepath"
)
type MyValid struct {
Sig []byte
Msg []byte
}
//upload and return new key cryptoed
func PostFile(filename, url string, valid *MyValid) []byte {
buf1 := bytes.NewBufferString("")
multi1 := multipart.NewWriter(buf1)
//multi1.CreateFormField("sig")
multi1.WriteField("sig", hex.EncodeToString(valid.Sig))
//multi1.CreateFormField("msg")
multi1.WriteField("msg", hex.EncodeToString(valid.Msg))
part, err := multi1.CreateFormFile("upfile", filepath.Base(filename))
if err != nil {
log.Println(err)
return nil
}
//boundary1 := multi1.Boundary()
//close_boundary := fmt.Sprintf("\n\r--%v--\b\r", boundary1)
//close_buf := bytes.NewBufferString(close_boundary)
//file
fp, err := os.Open(filename)
if err != nil {
log.Println(err)
return nil
}
defer fp.Close()
io.Copy(part, fp)
multi1.Close()
//info1, _ := fp.Stat()
//fsize := info1.Size()
//multireader
//mr1 := io.MultiReader(buf1, fp, close_buf)
//body_size := fsize + int64(buf1.Len()) + int64(close_buf.Len())
req, err := http.NewRequest("POST", url, buf1)
if err != nil {
log.Println(err)
return nil
}
req.Header.Add("Content-Type", multi1.FormDataContentType())
//req.ContentLength = body_size
res, err := http.DefaultClient.Do(req)
//end upload
//get response
buf2 := bytes.NewBufferString("")
buf2.ReadFrom(res.Body)
res.Body.Close()
retb := buf2.Bytes()
if bytes.Compare(retb[:4], []byte("fail")) == 0 {
log.Println(string(retb))
return nil
} else {
return retb[3:]
}
}