/
web.go
59 lines (50 loc) · 1.36 KB
/
web.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
package main
import (
"bytes"
"compress/gzip"
"fmt"
"html/template"
"log"
"net/http"
"github.com/tdewolff/minify"
"github.com/tdewolff/minify/html"
)
func HandleHtml(book Book) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Encoding", "gzip")
w.Header().Set("Vary", "Accept-Encoding")
w.Header().Set("Content-Type", "text/html; charset=utf-8")
// var zipBuff bytes.Buffer
// gz := gzip.NewWriter(&zipBuff)
gz := gzip.NewWriter(w)
defer gz.Close()
tmpl, err := template.ParseFiles("index.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var buf bytes.Buffer
err = tmpl.Execute(&buf, book)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
m := minify.New()
m.AddFunc("text/html", html.Minify)
minifiedHTML, err := m.String("text/html", buf.String())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
gz.Write([]byte(minifiedHTML))
// log.Println(len(buf.String()), len(minifiedHTML), len(zipBuff.Bytes()))
}
}
// Send HTML
func (app *App) Send(book Book) {
log.Println("Sending html")
http.HandleFunc("/", HandleHtml(book))
port := fmt.Sprintf(":%s", app.port)
log.Printf("Listening on port %s\n", app.port)
log.Fatal(http.ListenAndServe(port, nil))
}