forked from cpacia/BitcoinCash-Wallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
81 lines (67 loc) · 1.8 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
package bootstrap
import (
"net"
"net/http"
"text/template"
"path/filepath"
"github.com/asticode/go-astilog"
"github.com/asticode/go-astitools/template"
"github.com/julienschmidt/httprouter"
)
// Vars
var (
templates *template.Template
)
// serve initialize an HTTP server
func serve(baseDirectoryPath string, fnR AdaptRouter, fnT TemplateData) (ln net.Listener) {
// Init router
var r = httprouter.New()
// Static files
r.ServeFiles("/static/*filepath", http.Dir(filepath.Join(baseDirectoryPath, "resources", "static")))
// Dynamic pages
r.GET("/templates/*page", handleTemplates(fnT))
// Adapt router
if fnR != nil {
fnR(r)
}
// Parse templates
var err error
if templates, err = astitemplate.ParseDirectory(filepath.Join(baseDirectoryPath, "resources", "templates"), ".html"); err != nil {
astilog.Fatal(err)
}
// Listen
if ln, err = net.Listen("tcp", "127.0.0.1:"); err != nil {
astilog.Fatal(err)
}
astilog.Debugf("Listening on %s", ln.Addr())
// Serve
go http.Serve(ln, r)
return
}
// handleTemplate handles templates
func handleTemplates(fn TemplateData) httprouter.Handle {
return func(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {
// Check if template exists
var name = p.ByName("page") + ".html"
if templates.Lookup(name) == nil {
rw.WriteHeader(http.StatusNotFound)
return
}
// Get data
var d interface{}
var err error
if fn != nil {
if d, err = fn(name, r, p); err != nil {
astilog.Errorf("%s while retrieving data for template %s", err, name)
rw.WriteHeader(http.StatusInternalServerError)
return
}
}
// Execute template
if err = templates.ExecuteTemplate(rw, name, d); err != nil {
astilog.Errorf("%s while handling template %s", err, name)
rw.WriteHeader(http.StatusInternalServerError)
return
}
}
}