/
server.go
52 lines (43 loc) · 976 Bytes
/
server.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 (
"html/template"
"log"
"net/http"
"os"
"path"
)
func main() {
fs := http.FileServer(http.Dir("public"))
http.Handle("/public/", http.StripPrefix("/public/", fs))
http.HandleFunc("/", serveTemplate)
port := ":1337"
log.Println("Listening on port %s", port)
http.ListenAndServe(port, nil)
}
func serveTemplate(w http.ResponseWriter, r *http.Request) {
lp := path.Join("templates", "layout.html")
fp := path.Join("templates", r.URL.Path)
// request template is 404
info, err := os.Stat(fp)
if err != nil {
if os.IsNotExist(err) {
http.NotFound(w, r)
return
}
}
// Req is a directory, 404
if info.IsDir() {
http.NotFound(w, r)
return
}
tmpl, err := template.ParseFiles(lp, fp)
if err != nil {
log.Println(err.Error())
http.Error(w, http.StatusText(500), 500)
return
}
if err := tmpl.ExecuteTemplate(w, "layout", nil); err != nil {
log.Println(err.Error())
http.Error(w, http.StatusText(500), 500)
}
}