forked from poseidon/matchbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generic.go
77 lines (69 loc) · 2.01 KB
/
generic.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
package http
import (
"bytes"
"net/http"
"strings"
"time"
"context"
"github.com/Sirupsen/logrus"
"github.com/coreos/matchbox/matchbox/server"
pb "github.com/coreos/matchbox/matchbox/server/serverpb"
)
// genericHandler returns a handler that responds with the generic config
// matching the request.
func (s *Server) genericHandler(core server.Server) ContextHandler {
fn := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
group, err := groupFromContext(ctx)
if err != nil {
s.logger.WithFields(logrus.Fields{
"labels": labelsFromRequest(nil, req),
}).Infof("No matching group")
http.NotFound(w, req)
return
}
profile, err := core.ProfileGet(ctx, &pb.ProfileGetRequest{Id: group.Profile})
if err != nil {
s.logger.WithFields(logrus.Fields{
"labels": labelsFromRequest(nil, req),
"group": group.Id,
"group_name": group.Name,
}).Infof("No profile named: %s", group.Profile)
http.NotFound(w, req)
return
}
contents, err := core.GenericGet(ctx, profile.GenericId)
if err != nil {
s.logger.WithFields(logrus.Fields{
"labels": labelsFromRequest(nil, req),
"group": group.Id,
"group_name": group.Name,
"profile": group.Profile,
}).Infof("No generic template named: %s", profile.GenericId)
http.NotFound(w, req)
return
}
// match was successful
s.logger.WithFields(logrus.Fields{
"labels": labelsFromRequest(nil, req),
"group": group.Id,
"profile": profile.Id,
}).Debug("Matched a generic template")
// collect data for rendering
data, err := collectVariables(req, group)
if err != nil {
s.logger.Errorf("error collecting variables: %v", err)
http.NotFound(w, req)
return
}
// render the template of a generic config with data
var buf bytes.Buffer
err = s.renderTemplate(&buf, data, contents)
if err != nil {
http.NotFound(w, req)
return
}
config := buf.String()
http.ServeContent(w, req, "", time.Time{}, strings.NewReader(config))
}
return ContextHandlerFunc(fn)
}