-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.go
More file actions
59 lines (48 loc) · 1.34 KB
/
server.go
File metadata and controls
59 lines (48 loc) · 1.34 KB
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
package main
import (
"os"
"os/exec"
"io"
"fmt"
"log"
"bytes"
"net/http"
"github.com/satori/go.uuid"
)
func pdfHandler(rw http.ResponseWriter, req *http.Request) {
// create temp file
tmpHtml := "/tmp/" + uuid.NewV4().String() + ".html"
tmpPdf := "/tmp/" + uuid.NewV4().String() + ".pdf"
tmpHtmlFile, err := os.Create(tmpHtml)
if err != nil {
log.Fatal(err)
}
defer os.Remove(tmpHtml) // delete it after function exit
defer os.Remove(tmpPdf) // ...
// save content from request body to the file
io.Copy(tmpHtmlFile, req.Body)
tmpHtmlFile.Close()
size:= req.URL.Query().Get("size")
if size == "" {
size = "25cm*25cm"
}
// run phantomjs
cmd := exec.Command("phantomjs", "--ssl-protocol=any", "--ignore-ssl-errors=true", "rasterize.js", tmpHtml, tmpPdf, size)
var stderr, stdout bytes.Buffer
cmd.Stderr = &stderr
cmd.Stderr = &stdout
err = cmd.Run()
if err != nil {
log.Fatal(fmt.Sprint(err) + ": " + stderr.String() + "; " + stdout.String())
}
// send generated pdf in http response
tmpPdfFile, err := os.Open(tmpPdf)
if err != nil {
log.Fatal(err)
}
io.Copy(rw, tmpPdfFile)
}
func main() {
http.HandleFunc("/pdf", pdfHandler)
log.Fatal(http.ListenAndServe(":7777", nil))
}