-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
92 lines (79 loc) · 1.82 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
package main
import (
"bytes"
"embed"
"flag"
"fmt"
"html/template"
"log"
"net/http"
"strings"
"time"
)
type Server struct {
*template.Template
}
func NewServer(t *template.Template) (*Server, error) {
s := &Server{
Template: t,
}
return s, nil
}
func (s *Server) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
switch req.Method {
case http.MethodGet:
s.handleGet(rw, req)
default:
methods := []string{http.MethodGet}
rw.Header().Set("Accept", strings.Join(methods, ", "))
http.Error(rw, "invalid request method", http.StatusMethodNotAllowed)
}
}
func (s *Server) handleGet(rw http.ResponseWriter, req *http.Request) {
var bb bytes.Buffer
contentType := selectContentType(req, "text/plain", "text/html")
switch contentType {
case "text/plain":
fmt.Fprintln(&bb, "plain text response!")
case "text/html":
err := s.Execute(&bb, nil)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
default:
http.Error(rw, "failed to select content type", http.StatusInternalServerError)
return
}
br := bytes.NewReader(bb.Bytes())
http.ServeContent(rw, req, "", time.Now(), br)
}
//go:embed index.html
var embedIndexHTML string
//go:embed static
var embedStatic embed.FS
func main() {
var (
listen = ":8080"
)
flag.StringVar(&listen, "listen", listen, "server listen address")
flag.Parse()
funcs := map[string]interface{}{}
t, err := template.New("t").Funcs(funcs).Parse(embedIndexHTML)
if err != nil {
log.Fatalf("Error: %s", err)
}
sv, err := NewServer(t)
if err != nil {
log.Fatalf("Error: %s", err)
}
mux := http.NewServeMux()
mux.Handle("/static/", http.StripPrefix("/", http.FileServer(http.FS(embedStatic))))
mux.Handle("/", sv)
lgr := NewLogger(mux)
hsv := &http.Server{
Addr: listen,
Handler: lgr,
}
log.Fatal(hsv.ListenAndServe())
}