-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_http_test.go
More file actions
103 lines (86 loc) · 2.3 KB
/
example_http_test.go
File metadata and controls
103 lines (86 loc) · 2.3 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
package apitpl_test
import (
"fmt"
"io/fs"
"html/template"
"log"
"net/http"
"net/http/httptest"
"github.com/apisite/apitpl"
"github.com/apisite/apitpl/lookupfs"
// samplefs "github.com/apisite/apitpl/testdata"
"github.com/apisite/apitpl/samplemeta"
)
// Handle set of templates via http
func Example_http() {
// BufferPool size for rendered templates
const bufferSize int = 64
cfg := lookupfs.Config{
Includes: "includes",
Layouts: "layouts",
Pages: "pages",
Ext: ".html",
DefLayout: "default",
}
funcs := template.FuncMap{
"request": func() http.Request {
return http.Request{}
},
"content": func() template.HTML { return template.HTML("") },
}
embedDirFS,_ := fs.Sub(embedFS, "testdata")
tfs, err := apitpl.New(bufferSize).
Funcs(funcs).
LookupFS(
lookupfs.New(cfg).
FileSystem(embedDirFS)).
ParseAlways(true).
Parse()
if err != nil {
log.Fatal(err)
}
router := http.NewServeMux()
for _, uri := range tfs.PageNames(false) {
router.HandleFunc("/"+uri, handleHTML(tfs, uri))
}
resp := httptest.NewRecorder()
req, err := http.NewRequest("GET", "/subdir3/page", nil)
if err != nil {
log.Fatal(err)
}
router.ServeHTTP(resp, req)
fmt.Println(resp.Code)
fmt.Println(resp.Header().Get("Content-Type"))
fmt.Println(resp.Body.String())
// Output:
// 200
// text/html; charset=utf-8
// <title>Template title</title>
// ==
// page2 here (inc2 here)==inc1 (URI: /subdir3/page)
}
// handleHTML returns page handler
func handleHTML(tfs *apitpl.TemplateService, uri string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
// log.Debugf("Handling page (%s)", uri)
page := samplemeta.NewMeta(http.StatusOK, "text/html; charset=utf-8")
funcs := template.FuncMap{
"request": func() http.Request {
return *r
},
}
content := tfs.RenderContent(uri, funcs, page)
if page.Status() == http.StatusMovedPermanently || page.Status() == http.StatusFound {
http.Redirect(w, r, page.Title, page.Status())
return
}
header := w.Header()
header["Content-Type"] = []string{page.ContentType()}
w.WriteHeader(page.Status())
funcs["content"] = func() template.HTML { return template.HTML(content.Bytes()) }
err := tfs.Render(w, funcs, page, content)
if err != nil {
log.Fatal(err)
}
}
}