This repository has been archived by the owner on Jul 11, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
98 lines (85 loc) · 2.14 KB
/
main.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
package main
import (
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
)
const (
DioExportServer = "http://localhost:8000"
ConvertType = "png"
)
func main() {
rootDir := "input"
destDir := "output"
filepath.Walk(rootDir, func(path string, info os.FileInfo, err error) error {
rel, _ := filepath.Rel(rootDir, path)
if info.IsDir() {
os.Mkdir(filepath.Join(destDir, rel), os.ModePerm)
} else {
// TODO: check ext (.dio, ???, ...)
if err := convert(rootDir, destDir, rel, ConvertType); err != nil {
log.Printf("ERR: %v", err)
}
}
return nil
})
}
func convert(origin, dest, rel, ext string) error {
originFilePath := filepath.Join(origin, rel)
new, err := getNewFilename(rel, ext)
if err != nil {
return err
}
destFilePath := filepath.Join(dest, new)
out, err := os.Create(destFilePath)
if err != nil {
return fmt.Errorf("failed to create dest file: %w", err)
}
// Set up request
form := url.Values{}
form.Add("format", ext)
xml, err := ioutil.ReadFile(originFilePath)
if len(xml) == 0 {
return fmt.Errorf("input file is empty: %s", originFilePath)
}
if err != nil {
return fmt.Errorf("failed to read file: %w", err)
}
form.Add("xml", string(xml))
body := strings.NewReader(form.Encode())
req, err := http.NewRequest(http.MethodPost, DioExportServer, body)
if err != nil {
return fmt.Errorf("failed to create a request: %w", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
// Send request
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
return fmt.Errorf("encountered unexpected error: %w", err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return fmt.Errorf("request is failed with status code: %s", res.Status)
}
// Write results
_, err = io.Copy(out, res.Body)
if err != nil {
return fmt.Errorf("failed to copy response body to file: %w", err)
}
return nil
}
func getNewFilename(rel, ext string) (string, error) {
idx := strings.LastIndex(rel, ".")
if idx < 0 {
return "", fmt.Errorf("file doen't have any ext: %s", rel)
}
new := rel[:idx]
return fmt.Sprintf("%s.%s", new, ext), nil
}