-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
180 lines (163 loc) · 4.15 KB
/
request.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
package sypht
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"strings"
)
//UploadResponse response struct
type UploadResponse struct {
FileID string `json:"fileId"`
UploadedAt string `json:"uploadedAt"`
Status string `json:"status"`
Message string `json:"message"`
Code string `json:"code"`
}
// Upload uploads files with fileName
// options are list of fieldSets constant
func (s *Client) Upload(fileName string, options []string, workflowID string) (resp UploadResponse, err error) {
payload := &bytes.Buffer{}
writer := multipart.NewWriter(payload)
file, err := os.Open(fileName)
if err != nil {
return
}
defer file.Close()
cType, err := getFileContentType(file)
if err != nil {
log.Println(err)
return
}
ok := validateFileFormat(cType, filepath.Ext(strings.TrimSpace(fileName)))
if !ok {
err = fmt.Errorf("unsupported file : %s", fileName)
return
}
part, err := writer.CreateFormFile("fileToUpload", filepath.Base(fileName))
if err != nil {
return
}
_, err = io.Copy(part, file)
if err != nil {
return
}
fieldSets := parseOptions(options)
err = writer.WriteField("fieldSets", fieldSets)
if err != nil {
return
}
if workflowID != "" {
_ = writer.WriteField("workflowId", workflowID)
}
err = writer.Close()
if err != nil {
return
}
req, err := http.NewRequest("POST", s.config.apiBaseURL+"/fileupload", payload)
if err != nil {
return
}
req.Header.Add("Accept", "application/json")
req.Header.Add("Authorization", strings.Join([]string{"Bearer ", s.getToken()}, ""))
req.Header.Set("Content-Type", writer.FormDataContentType())
res, err := s.httpClient.Do(req)
if err != nil {
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return
}
err = json.Unmarshal(body, &resp)
return
}
// Results fetches results of uploaded file
func (s *Client) Results(fileID string) (out map[string]interface{}, err error) {
url := strings.Join([]string{s.config.apiBaseURL, "/result/final/", fileID}, "")
req, err := http.NewRequest("GET", url, strings.NewReader(""))
if err != nil {
return
}
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", strings.Join([]string{"Bearer ", s.getToken()}, ""))
res, err := s.httpClient.Do(req)
if err != nil {
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return
}
json.Unmarshal(body, &out)
return
}
// Image retrieves an image copy of the uploaded document.
func (s *Client) Image(fileID string, page int) (file []byte, err error) {
if page <= 0 {
page = 1
}
queryParam := fmt.Sprintf("?page=%d", page)
url := strings.Join([]string{s.config.apiBaseURL, "/result/image/", fileID, queryParam}, "")
log.Printf("get image url %s", url)
req, err := http.NewRequest("GET", url, strings.NewReader(""))
if err != nil {
return
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", strings.Join([]string{"Bearer ", s.getToken()}, ""))
res, err := s.httpClient.Do(req)
if err != nil {
return
}
defer res.Body.Close()
file, err = ioutil.ReadAll(res.Body)
if err != nil {
return
}
return
}
//PrettyPrintResponse pretty printing
func PrettyPrintResponse(mp map[string]interface{}) {
b, err := json.MarshalIndent(mp, "", " ")
if err != nil {
fmt.Println("error:", err)
}
fmt.Print(string(b))
}
func parseOptions(options []string) string {
if len(options) == 0 {
return "[]"
}
return "[" + strings.Join(options, ",") + "]"
}
func validateFileFormat(format, ext string) (ok bool) {
ext = strings.ToLower(ext)
supportedType := []string{"application/pdf", "image/jpeg", "image/png", "image/gif"}
for _, t := range supportedType {
if t == format {
return true
}
}
// have to check extension for tiff file since image/tiff not supported in go's mime contentType
return ext == ".tiff"
}
func getFileContentType(out *os.File) (contentType string, err error) {
buffer := make([]byte, 512)
_, err = out.Read(buffer)
if err != nil {
return
}
out.Seek(0, 0)
contentType = http.DetectContentType(buffer)
return
}