-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathviewmodel.go
52 lines (42 loc) · 1.21 KB
/
viewmodel.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
package main
import (
"fmt"
"net/http"
"text/template"
"github.com/aaaaaaaalex/ghp/util"
)
// implmentation of indexServer's viewmodel interface
type indexViewmodel struct {
data interface{} // can be any structure accepted as data by text/template.Execute
funcs template.FuncMap
}
/* Data is used exclusively to expose the contents of the directory being served.
this conveniently allows templates to reference the "current dir" with a dot.
See sample index file for elaboration.
*/
func (v indexViewmodel) Data() interface{} {
return v.data
}
// Funcs provides readonly access to state (e.g. the request)
func (v indexViewmodel) Funcs() template.FuncMap {
return v.funcs
}
// NewIndexViewmodel builds a new indexviewmodel for request r, implements ViewmodelBuilder
func NewIndexViewmodel(r *http.Request, dir http.File) (v Viewmodel, err error) {
// expose the index's siblings
siblings, err := dir.Readdir(0)
if err != nil {
return v, fmt.Errorf("Error reading index's directory: %s", err.Error())
}
funcMap := template.FuncMap{
"Request": func() *http.Request {
return r
},
"BaseURL": util.BaseURL,
}
v = indexViewmodel {
data: siblings,
funcs: funcMap,
}
return v, nil
}