-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathserve.go
55 lines (43 loc) · 1.08 KB
/
serve.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
package main
import (
"fmt"
"log"
"strconv"
"strings"
"math/rand"
"net/http"
"text/template"
"gopkg.in/loremipsum.v1"
)
func (opt *options) serve() {
http.HandleFunc("/", opt.page)
http.FileServer(http.FS(res))
log.Printf("Server listening at %s:%d...\n", opt.host, opt.port)
if err := http.ListenAndServe(fmt.Sprint(opt.host, ":", strconv.Itoa(opt.port)), nil); err != nil {
log.Fatal(err)
}
}
func (opt *options) page(w http.ResponseWriter, r *http.Request) {
li := loremipsum.NewWithSeed(rand.Int63())
page, ok := pages[r.URL.Path]
if !ok {
log.Printf(Err404, r.RequestURI, "")
w.WriteHeader(http.StatusNotFound)
return
}
tpl, err := template.ParseFS(res, page)
if err != nil {
log.Printf(Err404, r.RequestURI, "in pages cache")
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusOK)
data := map[string]interface{}{
"lorem_ipsum": strings.Replace(li.Paragraphs(10), `\n`, `<br><br>`, -1),
"PAYLOAD": opt.payload,
}
if err := tpl.Execute(w, data); err != nil {
return
}
}