-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
70 lines (62 loc) · 1.92 KB
/
Copy pathserver.go
File metadata and controls
70 lines (62 loc) · 1.92 KB
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
package api
import (
"context"
"crypto/subtle"
"net/http"
"time"
)
const ControllerName = "operator-api"
// Server exposes a minimal HTTP API for managing operator resources.
// It implements manager.Runnable so controller-runtime starts it alongside controllers.
// TLS is terminated at the ingress/NLB layer; the server listens on plain HTTP.
type Server struct {
handler http.Handler
addr string
}
func NewServer(addr, user, pass string, h *Handlers) *Server {
mux := http.NewServeMux()
mux.HandleFunc("GET /redirects", h.list)
mux.HandleFunc("POST /redirects", h.create)
mux.HandleFunc("GET /redirects/{domain}", h.get)
mux.HandleFunc("DELETE /redirects/{domain}", h.delete)
mux.HandleFunc("GET /redirects/{domain}/check", h.check)
return &Server{
addr: addr,
handler: basicAuth(user, pass, mux),
}
}
func (s *Server) Start(ctx context.Context) error {
srv := &http.Server{
Addr: s.addr,
Handler: s.handler,
ReadHeaderTimeout: 10 * time.Second,
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 120 * time.Second,
}
go func() {
<-ctx.Done()
_ = srv.Shutdown(context.Background()) //nolint:contextcheck
}()
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
return err
}
return nil
}
func (s *Server) NeedLeaderElection() bool { return false }
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.handler.ServeHTTP(w, r)
}
func basicAuth(user, pass string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
u, p, ok := r.BasicAuth()
if !ok ||
subtle.ConstantTimeCompare([]byte(u), []byte(user)) != 1 ||
subtle.ConstantTimeCompare([]byte(p), []byte(pass)) != 1 {
w.Header().Set("WWW-Authenticate", `Basic realm="operator-api"`)
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}