-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
68 lines (57 loc) · 1.4 KB
/
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main
import (
"context"
"log"
"net/http"
)
type server struct {
server *http.Server
servedDir string
shutdown chan bool
err chan error
}
func NewServer(address, servedDir string) *server {
return &server{
server: &http.Server{Addr: address},
servedDir: servedDir,
shutdown: make(chan bool, 1),
err: make(chan error, 1),
}
}
func (s *server) Start() error {
s.registerHandlers()
return s.serve()
}
func (s *server) registerHandlers() {
http.Handle("/files/", http.StripPrefix("/files", http.FileServer(http.Dir(s.servedDir))))
http.Handle("/filelist", NewFileListHandler(s.servedDir))
http.HandleFunc("/shutdown", s.shutdownHandler)
http.HandleFunc("/health", func(response http.ResponseWriter, req *http.Request) {})
}
func (s *server) serve() error {
go func() {
log.Printf("Serving %s\n", s.servedDir)
log.Printf("Listening on %s\n", s.server.Addr)
if err := s.server.ListenAndServe(); err != nil {
log.Printf("Finished listening: %s\n", err)
if err == http.ErrServerClosed {
close(s.err)
} else {
s.err <- err
}
}
}()
select {
case err := <-s.err:
return err
case <-s.shutdown:
if err := s.server.Shutdown(context.Background()); err != nil {
log.Printf("Error while shutting down the server: %s\n", err)
return err
}
}
return nil
}
func (s *server) shutdownHandler(http.ResponseWriter, *http.Request) {
s.shutdown <- true
}