-
Notifications
You must be signed in to change notification settings - Fork 1
/
input_uri.go
94 lines (83 loc) · 2.33 KB
/
input_uri.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
package modzy
import (
"encoding/base64"
"fmt"
"io"
"strings"
"github.com/pkg/errors"
)
// URIEncodable is a data input that can be provided when using Jobs().SubmitJobEmbedded(...).
//
// Provided implementations of this function are:
// (already encoded values)
// URIEncodedReader
// URIEncodedString
// URIEncodedFile
//
// (values to be URI encoded)
// URIEncodeReader
// URIEncodeString
// URIEncodeString
// URIEncodeFile
type URIEncodable func() (io.Reader, error)
func URIEncodedReader(alreadyEncoded io.Reader) URIEncodable {
return func() (io.Reader, error) {
return alreadyEncoded, nil
}
}
func URIEncodedString(alreadyEncoded string) URIEncodable {
return func() (io.Reader, error) {
return strings.NewReader(alreadyEncoded), nil
}
}
func URIEncodedFile(alreadyEncodedFilename string) URIEncodable {
return func() (io.Reader, error) {
file, err := AppFs.Open(alreadyEncodedFilename)
if err != nil {
return nil, errors.WithMessagef(err, "Failed to open file: %s", alreadyEncodedFilename)
}
return URIEncodedReader(file)()
}
}
func URIEncodeReader(notEncodedReader io.Reader, mimeType string) URIEncodable {
return func() (io.Reader, error) {
if mimeType == "" {
mimeType = "application/octet-stream"
}
sourceBytes, err := io.ReadAll(notEncodedReader)
if err != nil {
return nil, errors.WithMessage(err, "failed to read source data")
}
sourceBase64 := base64.StdEncoding.EncodeToString(sourceBytes)
return strings.NewReader(fmt.Sprintf(`data:%s;base64,%s`, mimeType, sourceBase64)), nil
}
}
func URIEncodeString(notEncodedString string, mimeType string) URIEncodable {
return URIEncodeReader(strings.NewReader(notEncodedString), mimeType)
}
func URIEncodeFile(filename string, mimeType string) URIEncodable {
return func() (io.Reader, error) {
if mimeType == "" {
mimeType = detectMimeType(filename)
}
file, err := AppFs.Open(filename)
if err != nil {
return nil, errors.WithMessagef(err, "Failed to open file: %s", filename)
}
return URIEncodeReader(file, mimeType)()
}
}
func detectMimeType(filename string) string {
split := strings.Split(filename, ".")
extension := split[len(split)-1]
// TODO what are common extensions to detect for this type of data?
switch extension {
case "jpg":
fallthrough
case "jpeg":
return "image/jpeg"
case "png":
return "image/png"
}
return ""
}