This repository has been archived by the owner on Mar 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
files.go
80 lines (63 loc) · 1.64 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
79
80
//********************************************************************************************************************//
//
// Copyright (C) 2018 - 2021 J&J Ideenschmiede GmbH <[email protected]>
//
// 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 AddFile(file *os.File, name string, token 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 := Config{"/v1/files/", "POST", token, writer.FormDataContentType(), body}
// Send request
response, err := c.Send()
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
}