-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
83 lines (77 loc) · 2.03 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package server
import (
"net"
"net/http"
"github.com/gorilla/mux"
"github.com/nathan-osman/caddy-docker/configurator"
"github.com/nathan-osman/caddy-docker/docker"
"github.com/sirupsen/logrus"
)
// Server provides a web interface for interacting with the application.
type Server struct {
username string
password string
configurator *configurator.Configurator
monitor *docker.Monitor
router *mux.Router
listener net.Listener
log *logrus.Entry
stopped chan bool
}
// New creates a new server.
func New(cfg *Config) (*Server, error) {
l, err := net.Listen("tcp", cfg.Addr)
if err != nil {
return nil, err
}
var (
srv = http.Server{}
router = mux.NewRouter()
s = &Server{
username: cfg.Username,
password: cfg.Password,
configurator: cfg.Configurator,
monitor: cfg.Monitor,
router: router,
listener: l,
log: logrus.WithField("context", "server"),
stopped: make(chan bool),
}
)
srv.Handler = s
router.HandleFunc("/", s.index)
router.HandleFunc("/api", s.api)
router.PathPrefix("/static").Handler(http.FileServer(HTTP))
go func() {
defer close(s.stopped)
defer s.log.Info("HTTP server has stopped")
s.log.Info("starting HTTP server")
if err := srv.Serve(l); err != nil {
s.log.Error(err)
}
}()
return s, nil
}
// ServeHTTP ensures that HTTP basic auth credentials match the requires ones
// and then routes the request to the muxer.
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/ping" {
w.Header().Set("Content-Length", "0")
w.WriteHeader(http.StatusOK)
return
}
if len(s.username) != 0 && len(s.password) != 0 {
u, p, ok := r.BasicAuth()
if !ok || u != s.username || p != s.password {
w.Header().Set("WWW-Authenticate", "Basic realm=caddy")
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
}
s.router.ServeHTTP(w, r)
}
// Close shuts down the server.
func (s *Server) Close() {
s.listener.Close()
<-s.stopped
}