-
Notifications
You must be signed in to change notification settings - Fork 10
/
server.go
271 lines (226 loc) · 6.58 KB
/
server.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
package main
import (
"bytes"
"encoding/json"
"net/http"
"os"
"text/template"
"time"
"github.com/Masterminds/sprig"
wk "github.com/SebastiaanKlippert/go-wkhtmltopdf"
"github.com/gin-contrib/zap"
"github.com/gin-gonic/gin"
"github.com/txn2/service/ginack"
"go.uber.org/zap"
)
type Page struct {
Location string `json:"location,omitempty"`
}
type Options struct {
FooterLeft string `json:"footer_left"`
FooterLeftRight string `json:"footer_right"`
CustomHeaders map[string]string `json:"custom_headers"`
CustomHeaderPropagation bool `json:"custom_header_propagation"`
PrintMediaType bool `json:"print_media_type"`
TocHeaderText string `json:"toc_header_text"`
TocXslSkip bool `json:"toc_xsl_skip"`
NoBackground bool `json:"no_background"`
JavascriptDelay uint `json:"javascript_delay"`
DisableJavascript bool `json:"disable_javascript"`
}
type Cfg struct {
Cover Page `json:"cover"`
TOC bool `json:"toc"`
Pages []Page `json:"pages"`
Options Options `json:"options"`
}
func main() {
var (
ip = getEnv("IP", "127.0.0.1")
port = getEnv("PORT", "8080")
debug = getEnv("DEBUG", "false")
tocXsl = getEnv("TOC_XSL", "")
)
gin.SetMode(gin.ReleaseMode)
if debug == "true" {
gin.SetMode(gin.DebugMode)
}
logger, err := zap.NewProduction()
if err != nil {
panic(err.Error())
}
if debug == "true" {
logger, _ = zap.NewDevelopment()
}
// router
r := gin.New()
// middleware
//
r.Use(ginzap.Ginzap(logger, time.RFC3339, true))
// routes
//
r.GET("/",
func(c *gin.Context) {
// call external libs for business logic here
ack := ginack.Ack(c)
ack.SetPayload(gin.H{"message": "pdf generator"})
// return
c.JSON(ack.ServerCode, ack)
return
},
)
r.POST("/getPdf",
func(c *gin.Context) {
ack := ginack.Ack(c)
rs, err := c.GetRawData()
if err != nil {
logger.Error("PostError: " + err.Error())
ack.ServerCode = 500
ack.SetPayload(gin.H{"status": "fail", "error": err.Error()})
c.JSON(ack.ServerCode, ack)
return
}
// parse raw json
tmpl, err := template.New("PostFilter").Funcs(sprig.TxtFuncMap()).Parse(string(rs))
if err != nil {
logger.Error("PostFilterError: " + err.Error())
ack.ServerCode = 500
ack.PayloadType = "PostFilterError"
ack.SetPayload(err.Error())
c.JSON(ack.ServerCode, ack)
return
}
var tplReturn bytes.Buffer
if err := tmpl.Execute(&tplReturn, c.Request); err != nil {
logger.Error("TemplateError: " + err.Error())
ack.ServerCode = 500
ack.PayloadType = "TemplateError"
ack.SetPayload(err.Error())
c.JSON(ack.ServerCode, ack)
return
}
cfg := &Cfg{}
err = json.Unmarshal(tplReturn.Bytes(), cfg)
if err != nil {
logger.Error("UnmarshalError: " + err.Error())
ack.ServerCode = 500
ack.PayloadType = "UnmarshalError"
ack.SetPayload(err.Error())
c.JSON(ack.ServerCode, ack)
return
}
// Create new PDF generator
pdfg, err := wk.NewPDFGenerator()
if err != nil {
logger.Error("PDFGeneratorError: " + err.Error())
ack.ServerCode = 500
ack.PayloadType = "UnmarshalError"
ack.SetPayload(err.Error())
c.JSON(ack.ServerCode, ack)
return
}
// configure a table of contents
if cfg.TOC {
logger.Info("Adding TOC")
pdfg.TOC.Include = true
pdfg.TOC.ExcludeFromOutline.Set(true)
pdfg.TOC.LoadMediaErrorHandling.Set("ignore")
pdfg.TOC.LoadErrorHandling.Set("ignore")
if len(cfg.Options.TocHeaderText) > 0 {
pdfg.TOC.TocHeaderText.Set(cfg.Options.TocHeaderText)
}
if tocXsl != "" && cfg.Options.TocXslSkip != true {
pdfg.TOC.XslStyleSheet.Set(tocXsl)
}
}
// add cover page if one exists
if len(cfg.Cover.Location) > 1 {
logger.Info("Adding cover: " + cfg.Cover.Location)
pdfg.Cover.Input = cfg.Cover.Location
pdfg.Cover.PrintMediaType.Set(true)
pdfg.Cover.LoadErrorHandling.Set("ignore")
pdfg.Cover.LoadMediaErrorHandling.Set("ignore")
for k, v := range cfg.Options.CustomHeaders {
logger.Info("Adding custom header to cover: k: " + k + " v: " + v)
pdfg.Cover.CustomHeader.Set(k, v)
pdfg.Cover.CustomHeaderPropagation.Set(cfg.Options.CustomHeaderPropagation)
}
}
// loop through page locations
for _, page := range cfg.Pages {
logger.Info("Adding page: " + page.Location)
p := &wk.Page{
Input: page.Location,
PageOptions: wk.NewPageOptions(),
}
p.EnableTocBackLinks.Set(true)
p.LoadErrorHandling.Set("ignore")
p.LoadMediaErrorHandling.Set("ignore")
p.FooterLeft.Set(cfg.Options.FooterLeft)
p.FooterRight.Set(cfg.Options.FooterLeftRight)
p.PrintMediaType.Set(cfg.Options.PrintMediaType)
p.JavascriptDelay.Set(cfg.Options.JavascriptDelay)
p.NoBackground.Set(cfg.Options.NoBackground)
p.DisableJavascript.Set(cfg.Options.NoBackground)
for k, v := range cfg.Options.CustomHeaders {
logger.Info("Adding custom header to page: k: " + k + " v: " + v)
p.CustomHeader.Set(k, v)
p.CustomHeaderPropagation.Set(cfg.Options.CustomHeaderPropagation)
}
pdfg.AddPage(p)
}
// Create PDF document in internal buffer
err = pdfg.Create()
if err != nil {
logger.Warn("RunError: " + err.Error())
// since wkhtmltopdf is not respecting the ignore on
// missing content we will suppress the error, log it and
// assume the pdf is acceptable.
// TODO: investigate
}
c.Header("Content-Type", "application/pdf")
c.String(http.StatusOK, string(pdfg.Bytes()))
},
)
// for external status check
r.GET("/status",
func(c *gin.Context) {
ack := ginack.Ack(c)
p := gin.H{"message": "alive"}
if c.Query("noack") == "true" {
c.JSON(200, p)
return
}
ack.SetPayload(p)
c.JSON(ack.ServerCode, ack)
},
)
// default no route
r.NoRoute(func(c *gin.Context) {
ack := ginack.Ack(c)
ack.SetPayload(gin.H{"message": "not found"})
ack.ServerCode = 404
ack.Success = false
// return
c.JSON(ack.ServerCode, ack)
})
logger.Info("Starting txPDF server",
zap.String("IP", ip),
zap.String("port", port),
zap.String("debug", debug),
zap.String("tocXsl", tocXsl),
)
err = r.Run(ip + ":" + port)
if err != nil {
logger.Fatal("could not start server", zap.Error(err))
}
}
// getEnv gets an environment variable or sets a default if
// one does not exist.
func getEnv(key, fallback string) string {
value := os.Getenv(key)
if len(value) == 0 {
return fallback
}
return value
}