This repository has been archived by the owner on Mar 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathhandler.go
84 lines (73 loc) · 2.05 KB
/
handler.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
package main
import (
"bytes"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"github.com/rs/xlog"
"github.com/rs/xmux"
"golang.org/x/net/context"
)
func healthHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
if checkUnoconv(uno) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("200 -OK"))
} else {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 -StatusInternalServerError"))
}
}
func unoconvHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
l := xlog.FromContext(ctx)
//The whole request body is parsed and up to a total of 34MB bytes of its file parts are stored in memory,
//with the remainder stored on disk in temporary files.
r.ParseMultipartForm(32 << 20)
file, handler, err := r.FormFile("file")
if err != nil {
l.Error(err)
return
}
defer file.Close()
//add the filename to access log
l.SetField("filename", handler.Filename)
extension := filepath.Ext(handler.Filename)
//create a temporary file, to copy the POSTed file data into it
tempfile, err := ioutil.TempFile(os.TempDir(), "unoconv-api*" + extension)
if err != nil {
l.Error(err)
return
}
defer os.Remove(tempfile.Name())
switch extension {
case ".txt":
//special handling for plain text files, try to detect the charset and convert to utf8
data, err := ioutil.ReadAll(file)
if err != nil {
l.Error(err)
return
}
//try to convert the textfile (data) to utf-8 and write it to tempfile
charset, err := toUTF8(data, tempfile)
l.SetField("charset", charset)
l.SetField("convertedToUTF8", true)
if err != nil {
//Could not convert to utf-8, write the original data to tempfile
l.Error(err)
l.SetField("convertedToUTF8", false)
io.Copy(tempfile, bytes.NewBuffer(data))
}
default:
//just copy all other file types
io.Copy(tempfile, file)
}
tempfile.Close()
//Run unoconv to convert the file
//unoconv's stdout is plugged directly to the httpResponseWriter
err = uno.convert(tempfile.Name(), xmux.Param(ctx, "filetype"), w)
if err != nil {
l.Error(err)
return
}
}