forked from poseidon/matchbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
metadata.go
71 lines (63 loc) · 1.83 KB
/
metadata.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
package http
import (
"fmt"
"io"
"net/http"
"strings"
"context"
"github.com/Sirupsen/logrus"
)
const plainContentType = "plain/text"
// genericHandler returns a handler that responds with the metadata env file
// matching the request.
func (s *Server) metadataHandler() 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
}
// match was successful
s.logger.WithFields(logrus.Fields{
"labels": labelsFromRequest(nil, req),
"group": group.Id,
}).Debug("Matched group metadata")
// 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
}
w.Header().Set(contentType, plainContentType)
renderAsEnvFile(w, "", data)
}
return ContextHandlerFunc(fn)
}
// renderAsEnvFile writes map data into a KEY=value\n "env file" format,
// descending recursively into nested maps and prepending parent keys.
//
// For example, {"outer":{"inner":"val"}} -> OUTER_INNER=val). Note that
// structure is lost in this transformation, the inverse transfom has two
// possible outputs.
func renderAsEnvFile(w io.Writer, prefix string, root map[string]interface{}) {
for key, value := range root {
name := prefix + key
switch val := value.(type) {
case string, bool, float64:
// simple JSON unmarshal types
fmt.Fprintf(w, "%s=%v\n", strings.ToUpper(name), val)
case map[string]string:
m := map[string]interface{}{}
for k, v := range val {
m[k] = v
}
renderAsEnvFile(w, name+"_", m)
case map[string]interface{}:
renderAsEnvFile(w, name+"_", val)
}
}
}