forked from jjideenschmiede/golexoffice
-
Notifications
You must be signed in to change notification settings - Fork 1
/
files.go
78 lines (61 loc) · 1.58 KB
/
files.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
//********************************************************************************************************************//
//
// This file is part of golexoffice.
// All code may be used. Feel free and maybe code something better.
//
// Author: Jonas Kwiedor (aka gowizzard)
//
//********************************************************************************************************************//
package golexoffice
import (
"bytes"
"encoding/json"
"io"
"mime/multipart"
"os"
)
// FileReturn is to decode json data
type FileReturn struct {
Id string `json:"id"`
}
// AddFile is to upload a file
func (c *Config) AddFile(file *os.File, name string) (FileReturn, error) {
// Create form data
body := &bytes.Buffer{}
// Create writer
writer := multipart.NewWriter(body)
// Create body data
filePart, err := writer.CreateFormFile("file", name)
if err != nil {
return FileReturn{}, err
}
// Copy form & file
_, err = io.Copy(filePart, file)
if err != nil {
return FileReturn{}, err
}
// Create text part
_ = writer.WriteField("type", "voucher")
// Close writer
err = writer.Close()
if err != nil {
return FileReturn{}, err
}
// Set config for new request
//c := NewConfig(, token, &http.Client{})
// Send request
response, err := c.Send("/v1/files/", body, "POST", writer.FormDataContentType())
if err != nil {
return FileReturn{}, err
}
// Close request
defer response.Body.Close()
// Decode data
var decode FileReturn
err = json.NewDecoder(response.Body).Decode(&decode)
if err != nil {
return FileReturn{}, err
}
// Return data
return decode, nil
}