forked from hound-search/hound
-
Notifications
You must be signed in to change notification settings - Fork 0
/
web.go
85 lines (70 loc) · 1.72 KB
/
web.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
package web
import (
"fmt"
"net/http"
"sync"
"github.com/hound-search/hound/api"
"github.com/hound-search/hound/config"
"github.com/hound-search/hound/searcher"
"github.com/hound-search/hound/ui"
)
// Server is an HTTP server that handles all
// http traffic for hound. It is able to serve
// some traffic before indexes are built and
// then transition to all traffic afterwards.
type Server struct {
cfg *config.Config
dev bool
ch chan error
mux *http.ServeMux
lck sync.RWMutex
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == s.cfg.HealthCheckURI {
fmt.Fprintln(w, "👍")
return
}
s.lck.RLock()
defer s.lck.RUnlock()
if m := s.mux; m != nil {
m.ServeHTTP(w, r)
} else {
http.Error(w,
"Hound is not ready.",
http.StatusServiceUnavailable)
}
}
func (s *Server) serveWith(m *http.ServeMux) {
s.lck.Lock()
defer s.lck.Unlock()
s.mux = m
}
// Start creates a new server that will immediately start handling HTTP traffic.
// The HTTP server will return 200 on the health check, but a 503 on every other
// request until ServeWithIndex is called to begin serving search traffic with
// the given searchers.
func Start(cfg *config.Config, addr string, dev bool) *Server {
ch := make(chan error)
s := &Server{
cfg: cfg,
dev: dev,
ch: ch,
}
go func() {
ch <- http.ListenAndServe(addr, s)
}()
return s
}
// ServeWithIndex allow the server to start offering the search UI and the
// search APIs operating on the given indexes.
func (s *Server) ServeWithIndex(idx map[string]*searcher.Searcher) error {
h, err := ui.Content(s.dev, s.cfg)
if err != nil {
return err
}
m := http.NewServeMux()
m.Handle("/", h)
api.Setup(m, idx)
s.serveWith(m)
return <-s.ch
}