-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi.go
More file actions
70 lines (65 loc) · 1.59 KB
/
api.go
File metadata and controls
70 lines (65 loc) · 1.59 KB
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
package pinata
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"strings"
)
type PinResponse struct {
IpfsHash string `json:"IpfsHash,omitempty"`
PinSize int64 `json:"PinSize,omitempty"`
Timestamp string `json:"Timestamp,omitempty"`
Error string `json:"error,omitempty"`
IsDuplicate bool `json:"isDuplicate,omitempty"`
}
func (c *Client) PinFile(filepath string) (PinResponse, error) {
b, w, err := createMultipartFormData(filepath)
req, _ := http.NewRequest("POST", c.Node+ApiPinFile, &b)
req.Header.Set("Authorization", "Bearer "+c.JWT)
req.Header.Set("Content-Type", w.FormDataContentType())
resp, err := (&http.Client{}).Do(req)
if err != nil {
return PinResponse{}, err
}
defer resp.Body.Close()
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
return PinResponse{}, err
}
fmt.Println("debug joy", string(content))
var out PinResponse
if err = json.Unmarshal(content, &out); err != nil {
return PinResponse{}, err
}
return out, nil
}
func createMultipartFormData(filePath string) (bytes.Buffer, *multipart.Writer, error) {
var b bytes.Buffer
var err error
w := multipart.NewWriter(&b)
var fw io.Writer
file, err := os.Open(filePath)
if err != nil {
return b, w, err
}
if fw, err = w.CreateFormFile("file", formatFilename(filePath)); err != nil {
return b, w, err
}
if _, err = io.Copy(fw, file); err != nil {
return b, w, err
}
w.Close()
return b, w, nil
}
func formatFilename(path string) string {
items := strings.Split(path, "/")
if len(items) > 0 {
return items[len(items)-1]
}
return ""
}