-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
74 lines (64 loc) · 1.71 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
package main
import (
"fmt"
"io"
"log"
"mime/multipart"
"net/http"
"os"
)
/**
* Declare the Web service handler. This is a frontend service
* that receives PDF files and convert them to HTML using PDF2HTMLEx
* returning the generated HTML source.
*/
func main() {
println("Starting server at :8080...")
http.HandleFunc("/", transformer)
http.HandleFunc("/healthcheck", healthcheck)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func transformer(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(405)
fmt.Fprintf(w, "This method is not allowed")
return
}
r.ParseMultipartForm(32 << 20)
uploaded, _, err := r.FormFile("pdf")
if err != nil && err == http.ErrMissingFile {
w.WriteHeader(400)
fmt.Fprintf(w, "%v", err)
return
}
defer uploaded.Close()
// Make a copy of the received pdf to a temporary file
tempFile, err := uploadedContentsToTempFile(uploaded)
if err != nil {
log.Printf("Could not store uploaded contents. %v", err)
fmt.Fprintf(w, "Could not store uploaded contents. %v", err)
return
}
// ConvertPDFToHTML uses PDF2HTMLEx to convert the uploaded file
HTMLOutput := ConvertPDFToHTML(tempFile)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprint(w, HTMLOutput)
// Free resources
err = os.Remove(tempFile)
if err != nil {
log.Printf("Could not delete file %s", tempFile)
}
}
func uploadedContentsToTempFile(uploadedFile multipart.File) (string, error) {
tempFile := TemporalFileName("pdf")
finalFile, err := os.Create(tempFile)
if err != nil {
return "", err
}
io.Copy(finalFile, uploadedFile)
finalFile.Close()
return tempFile, nil
}
func healthcheck(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "healthy")
}