forked from yuzutech/kroki-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate.go
60 lines (54 loc) · 1.56 KB
/
generate.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
package kroki
import (
"io/ioutil"
"os"
"github.com/pkg/errors"
)
const MAX_URI_LENGTH = 4096
// FromString takes a string and returns the image generated by Kroki
func (c *Client) FromString(input string, diagramType DiagramType, imageFormat ImageFormat) (string, error) {
payload, err := CreatePayload(input)
if err != nil {
return "", err
}
if len(payload) > MAX_URI_LENGTH {
return c.PostRequest(input, diagramType, imageFormat)
} else {
return c.GetRequest(payload, diagramType, imageFormat)
}
}
// FromFile takes a file path and returns the image generated by Kroki
func (c *Client) FromFile(path string, diagramType DiagramType, imageFormat ImageFormat) (string, error) {
content, err := ioutil.ReadFile(path)
if err != nil {
return "", errors.Wrapf(err, "fail to read file '%s'", path)
}
input := string(content)
payload, err := CreatePayload(input)
if err != nil {
return "", err
}
if len(payload) > MAX_URI_LENGTH {
return c.PostRequest(input, diagramType, imageFormat)
} else {
return c.GetRequest(payload, diagramType, imageFormat)
}
}
// WriteToFile takes a file path and a string
// write the string into the file
func (c *Client) WriteToFile(path string, result string) error {
file, err := os.Create(path)
if err != nil {
return errors.Wrapf(err, "fail to create file '%s'", path)
}
defer file.Close()
_, err = file.Write([]byte(result))
if err != nil {
return errors.Wrapf(err, "fail to write to file '%s'", path)
}
err = file.Sync()
if err != nil {
return errors.Wrapf(err, "fail to sync file '%s'", path)
}
return nil
}