forked from poseidon/matchbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
67 lines (60 loc) · 2.04 KB
/
handlers.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
package http
import (
"fmt"
"net/http"
"context"
"github.com/coreos/matchbox/matchbox/server"
pb "github.com/coreos/matchbox/matchbox/server/serverpb"
)
// homeHandler shows the server name for rooted requests. Otherwise, a 404 is
// returned.
func homeHandler() http.Handler {
fn := func(w http.ResponseWriter, req *http.Request) {
if req.URL.Path != "/" {
http.NotFound(w, req)
return
}
fmt.Fprintf(w, "matchbox\n")
}
return http.HandlerFunc(fn)
}
// logRequest logs HTTP requests.
func (s *Server) logRequest(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, req *http.Request) {
s.logger.Infof("HTTP %s %v", req.Method, req.URL)
next.ServeHTTP(w, req)
}
return http.HandlerFunc(fn)
}
// selectGroup selects the Group whose selectors match the query parameters,
// adds the Group to the ctx, and calls the next handler. The next handler
// should handle a missing Group.
func (s *Server) selectGroup(core server.Server, next ContextHandler) ContextHandler {
fn := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
attrs := labelsFromRequest(s.logger, req)
// match machine request
group, err := core.SelectGroup(ctx, &pb.SelectGroupRequest{Labels: attrs})
if err == nil {
// add the Group to the ctx for next handler
ctx = withGroup(ctx, group)
}
next.ServeHTTP(ctx, w, req)
}
return ContextHandlerFunc(fn)
}
// selectProfile selects the Profile for the given query parameters, adds the
// Profile to the ctx, and calls the next handler. The next handler should
// handle a missing profile.
func (s *Server) selectProfile(core server.Server, next ContextHandler) ContextHandler {
fn := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
attrs := labelsFromRequest(s.logger, req)
// match machine request
profile, err := core.SelectProfile(ctx, &pb.SelectProfileRequest{Labels: attrs})
if err == nil {
// add the Profile to the ctx for the next handler
ctx = withProfile(ctx, profile)
}
next.ServeHTTP(ctx, w, req)
}
return ContextHandlerFunc(fn)
}