forked from benrowe/books
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreview.go
107 lines (96 loc) · 2.34 KB
/
preview.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
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
"github.com/kjk/u"
)
func fileForURI(uri string) string {
path := filepath.Join("www", uri)
if u.FileExists(path) {
return path
}
path = path + ".html"
if u.FileExists(path) {
return path
}
return ""
}
func serve404(w http.ResponseWriter, r *http.Request) {
uri := r.URL.Path
path := filepath.Join("www", "404.html")
parts := strings.Split(uri[1:], "/")
if len(parts) > 2 && parts[0] == "essential" {
bookName := parts[1]
maybePath := filepath.Join("www", "essential", bookName, "404.html")
if u.FileExists(maybePath) {
fmt.Printf("'%s' exists\n", maybePath)
path = maybePath
} else {
fmt.Printf("'%s' doesn't exist\n", maybePath)
}
}
fmt.Printf("Serving 404 from '%s' for '%s'\n", path, uri)
d, err := ioutil.ReadFile(path)
if err != nil {
d = []byte(fmt.Sprintf("URL '%s' not found!", uri))
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(http.StatusNotFound)
w.Write(d)
}
func handleIndex(w http.ResponseWriter, r *http.Request) {
uri := r.URL.Path
if uri == "/" {
uri = "/index.html"
}
uriLocal := filepath.FromSlash(uri)
if !strings.HasSuffix(uri, ".png") {
fmt.Printf("uri: '%s'\n", uri)
}
path := fileForURI(uriLocal)
if path == "" {
serve404(w, r)
return
}
http.ServeFile(w, r, path)
}
// https://blog.gopheracademy.com/advent-2016/exposing-go-on-the-internet/
func makeHTTPServer() *http.Server {
mux := &http.ServeMux{}
mux.HandleFunc("/", handleIndex)
srv := &http.Server{
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
IdleTimeout: 120 * time.Second, // introduced in Go 1.8
Handler: mux,
}
return srv
}
func startPreviewStatic() {
fmt.Printf("startPreviewStatic()\n")
httpSrv := makeHTTPServer()
httpSrv.Addr = "127.0.0.1:8173"
go func() {
err := httpSrv.ListenAndServe()
// mute error caused by Shutdown()
if err == http.ErrServerClosed {
err = nil
}
u.Must(err)
fmt.Printf("HTTP server shutdown gracefully\n")
}()
fmt.Printf("Started listening on %s\n", httpSrv.Addr)
u.OpenBrowser("http://" + httpSrv.Addr)
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt /* SIGINT */, syscall.SIGTERM)
sig := <-c
fmt.Printf("Got signal %s\n", sig)
}