-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
125 lines (106 loc) · 3.54 KB
/
server.go
File metadata and controls
125 lines (106 loc) · 3.54 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
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
package httpdf
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"github.com/gorilla/handlers"
"github.com/sehrgutesoftware/httpdf/internal/template"
)
type server struct {
*http.ServeMux
httpdf HTTPDF
loader template.Loader
cache map[string]*template.Template
}
func NewServer(httpdf HTTPDF, loader template.Loader) http.Handler {
server := &server{
ServeMux: http.NewServeMux(),
httpdf: httpdf,
loader: loader,
cache: make(map[string]*template.Template),
}
server.Handle("POST /templates/{template}/render", http.HandlerFunc(server.render))
server.Handle("GET /templates/{template}/preview", http.HandlerFunc(server.preview))
server.Handle("GET /templates/{template}/assets/", http.HandlerFunc(server.assets))
cors := handlers.CORS(
handlers.AllowedOrigins([]string{"*"}),
handlers.AllowedMethods([]string{http.MethodOptions, http.MethodGet, http.MethodPost}),
handlers.AllowedHeaders([]string{"Content-Type"}),
)
return cors(server)
}
func (s *server) render(w http.ResponseWriter, r *http.Request) {
var values map[string]any
if err := json.NewDecoder(r.Body).Decode(&values); err != nil {
http.Error(w, "invalid request body", http.StatusBadRequest)
return
}
// For the render operation, the cached template is used
t, err := s.cachedTemplate(r.PathValue("template"))
if errors.Is(err, template.ErrTemplateNotFound) {
http.Error(w, "template not found", http.StatusNotFound)
return
} else if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/pdf")
if err := s.httpdf.Generate(r.Context(), t, extractLocale(r), values, w); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func (s *server) preview(w http.ResponseWriter, r *http.Request) {
assets := fmt.Sprintf("/templates/%s/assets", r.PathValue("template"))
// For the preview operation, the template is loaded each time in order to
// reflect any changes made to the template files.
t, err := s.loader.Load(r.PathValue("template"))
if errors.Is(err, template.ErrTemplateNotFound) {
http.Error(w, "template not found", http.StatusNotFound)
return
} else if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html")
err = t.Render(t.Example, assets, extractLocale(r), w)
if err != nil {
http.Error(w, "failed to render template: "+err.Error(), http.StatusInternalServerError)
return
}
}
func (s *server) assets(w http.ResponseWriter, r *http.Request) {
// Assets are served from the cached template because they are read from the
// filesystem on each request.
t, err := s.cachedTemplate(r.PathValue("template"))
if errors.Is(err, template.ErrTemplateNotFound) {
http.Error(w, "template not found", http.StatusNotFound)
return
} else if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if t.Assets == nil {
http.Error(w, "no assets available for this template", http.StatusNotFound)
return
}
prefix := fmt.Sprintf("/templates/%s/assets/", r.PathValue("template"))
http.StripPrefix(prefix, http.FileServer(http.FS(t.Assets))).ServeHTTP(w, r)
}
func (s *server) cachedTemplate(name string) (*template.Template, error) {
if t, ok := s.cache[name]; ok {
return t, nil
}
t, err := s.loader.Load(name)
if err != nil {
return nil, err
}
s.cache[name] = t
return t, nil
}
func extractLocale(r *http.Request) string {
if locale := r.URL.Query().Get("lang"); locale != "" {
return locale
}
return r.Header.Get("Accept-Language")
}