forked from Scripted/pandago
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
83 lines (71 loc) · 1.65 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
package main
import (
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/render"
)
func main() {
router := gin.Default()
router.StaticFile("/", "./static/index.html")
router.StaticFile("/favicon.ico", "./static/favicon.ico")
router.GET("/ping", ping)
router.POST("/convert", convert)
router.GET("/convert", func(c *gin.Context) {
c.Redirect(301, "/")
})
router.Run()
}
func ping(c *gin.Context) {
c.JSON(200, gin.H{"message": "OK 🐼, Go!"})
}
func convert(c *gin.Context) {
payload, _, err := c.Request.FormFile("payload")
if err != nil {
log.Panic(err)
}
inputFile := createTempFile("source_")
defer os.Remove(inputFile.Name())
io.Copy(inputFile, payload)
outputFile := createTempFile("converted_")
defer os.Remove(outputFile.Name())
args := []string{
"--standalone",
"--from", c.PostForm("from"),
"--to", c.PostForm("to"),
"--output", outputFile.Name(),
inputFile.Name(),
}
err = exec.Command("pandoc", args...).Run()
if err != nil {
log.Panic(err)
}
data, err := ioutil.ReadAll(outputFile)
if err != nil {
log.Panic(err)
}
c.Render(200, render.Data{ContentType: contentType(c.PostForm("to")), Data: data})
}
func createTempFile(prefix string) *os.File {
tempFile, err := ioutil.TempFile("", prefix)
if err != nil {
log.Fatal(err)
}
return tempFile
}
func contentType(format string) string {
switch format {
case "markdown":
return "text/markdown; charset=UTF-8"
case "html":
return "text/html; charset=utf-8"
case "docx":
return "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
default:
log.Panic("Unsupported format")
}
return ""
}