/
report_service_impl.go
77 lines (60 loc) · 2.15 KB
/
report_service_impl.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
package business
import (
"encoding/base64"
"encoding/json"
"fmt"
"github.com/AdikaStyle/go-report-builder/internal/data"
"github.com/palantir/stacktrace"
)
type reportService struct {
pdf data.ReportExporter
png data.ReportExporter
templateService TemplateService
baseUrl string
}
func (rs *reportService) ExportReportHtml(reportId string, data interface{}) ([]byte, error) {
html, err := rs.templateService.RenderTemplate(reportId, data)
if err != nil {
return nil, stacktrace.RootCause(err)
}
b64Html := base64.StdEncoding.EncodeToString(html)
return []byte(b64Html), nil
}
func (rs *reportService) ExportReportPdf(reportId string, data interface{}) ([]byte, error) {
url, err := rs.buildUrl(reportId, data)
if err != nil {
return nil, stacktrace.Propagate(err, "failed to build url for pdf export on reportId: %s and data: %+v", reportId, data)
}
pdf, _, err := rs.pdf.Export(url)
if err != nil {
return nil, stacktrace.RootCause(err)
}
b64Pdf := base64.StdEncoding.EncodeToString(pdf)
return []byte(b64Pdf), nil
}
func (rs *reportService) ExportReportPng(reportId string, data interface{}) ([]byte, error) {
url, err := rs.buildUrl(reportId, data)
if err != nil {
return nil, stacktrace.Propagate(err, "failed to build url for pdf export on reportId: %s and data: %+v", reportId, data)
}
png, _, err := rs.png.Export(url)
if err != nil {
return nil, stacktrace.RootCause(err)
}
b64Png := base64.StdEncoding.EncodeToString(png)
return []byte(b64Png), nil
}
func (rs *reportService) buildUrl(reportId string, data interface{}) (string, error) {
jsonData, err := json.Marshal(data)
if err != nil {
return "", stacktrace.Propagate(err, "failed to marshal %+v to json", data)
}
b64Data := base64.StdEncoding.EncodeToString(jsonData)
if b64Data == "e30=" {
b64Data = ""
}
return fmt.Sprintf("http://%s/reports/render/%s?d=%s", rs.baseUrl, reportId, b64Data), nil
}
func NewReportService(pdf data.ReportExporter, png data.ReportExporter, templateService TemplateService, baseUrl string) *reportService {
return &reportService{pdf: pdf, png: png, templateService: templateService, baseUrl: baseUrl}
}