summaryrefslogtreecommitdiff
path: root/internal/server/admin.go
blob: 46242d464e94680b35caaddf3ec09fc2133a033f (plain)
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
package server

import (
	"fmt"
	"log/slog"
	"net/http"
)

type Admin struct {
	server *http.Server
	s      *Server
}

func NewAdmin(listen string, s *Server) *Admin {
	if listen == "" {
		return nil
	}

	mux := http.NewServeMux()
	a := &Admin{
		server: &http.Server{
			Addr:    listen,
			Handler: mux,
		},
		s: s,
	}
	mux.HandleFunc("/health", a.healthHandler)
	return a
}

func (a *Admin) Start() {
	if a == nil {
		return
	}
	go func() {
		slog.Info("admin server listening", "addr", a.server.Addr)
		if err := a.server.ListenAndServe(); err != nil &&
			err != http.ErrServerClosed {
			slog.Error("admin server failed", "error", err)
		}
	}()
}

func (a *Admin) Close() error {
	if a == nil {
		return nil
	}
	return a.server.Close()
}

func (a *Admin) healthHandler(w http.ResponseWriter, r *http.Request) {
	if a.s == nil {
		http.Error(w, "not ready", http.StatusServiceUnavailable)
		return
	}
	if a.s.Ready() {
		w.WriteHeader(http.StatusOK)
		fmt.Fprint(w, "ok\n")
		return
	}
	http.Error(w, "not ready", http.StatusServiceUnavailable)
}