-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
126 lines (105 loc) · 2.42 KB
/
main.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
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
126
package main
import (
"flag"
"fmt"
"github.com/indigo-web/indigo"
"github.com/indigo-web/indigo/http"
"github.com/indigo-web/indigo/router/inbuilt"
"github.com/indigo-web/indigo/router/inbuilt/middleware"
"html/template"
"log"
"strings"
"sync"
)
const (
defaultAddr = ":80"
homeTmplPath = "templates/index.html"
homeDefaultName = "Паша"
)
var (
addr = flag.String(
"http", defaultAddr, "specify the server address",
)
https = flag.String(
"https", "",
"specify the https server address. Leave empty to not use HTTPS at all",
)
cert = flag.String(
"cert", "",
"specify custom server certificate instead of autocert",
)
)
type Index struct {
mu *sync.RWMutex
tmpl *template.Template
path string
}
func NewIndex(tmplPath string) (*Index, error) {
tmpl, err := template.ParseFiles(homeTmplPath)
if err != nil {
return nil, fmt.Errorf("cannot load home template: %s", err)
}
return &Index{
mu: new(sync.RWMutex),
tmpl: tmpl,
path: tmplPath,
}, nil
}
func (i *Index) Render(request *http.Request) *http.Response {
name, _ := request.Query.Get("name")
if len(name) == 0 {
name = homeDefaultName
}
resp := request.Respond()
i.mu.RLock()
defer i.mu.RUnlock()
if err := i.tmpl.Execute(resp, name); err != nil {
return http.Error(request, err)
}
return resp
}
func (i *Index) ReloadTemplate(request *http.Request) *http.Response {
i.mu.Lock()
defer i.mu.Unlock()
tmpl, err := template.ParseFiles(homeTmplPath)
if err != nil {
return http.Error(request, err)
}
i.tmpl = tmpl
return http.String(request, "reloaded the template successfully")
}
func main() {
flag.Parse()
index, err := NewIndex(homeTmplPath)
if err != nil {
log.Fatalf("parse index template: %s", err)
return
}
r := inbuilt.New().
Use(middleware.Recover).
Use(middleware.LogRequests()).
Get("/", index.Render).
Get("/reload-template", index.ReloadTemplate).
Static("/static", "static").
Alias("/age", "/static/age.html")
app := indigo.New(*addr)
if len(*https) > 0 {
if len(*cert) > 0 {
certificate, key := splitPaths(*cert)
app.HTTPS(*https, certificate, key)
} else {
app.AutoHTTPS(*https)
}
}
err = app.OnBind(func(addr string) {
log.Printf("listening on %s\n", addr)
}).Serve(r)
log.Fatal(err)
}
func splitPaths(paths string) (cert, key string) {
files := strings.SplitN(paths, ",", 2)
if len(files) < 2 {
panic("bad HTTPS cert and key pair")
}
return files[0], files[1]
}