This repository was archived by the owner on Sep 5, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathletit.go
More file actions
85 lines (74 loc) · 1.99 KB
/
letit.go
File metadata and controls
85 lines (74 loc) · 1.99 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"strings"
)
func resolveEnvironment(variableSpec string) map[string]interface{} {
// split and trim the input variables
specs := strings.Split(variableSpec, ",")
for i, s := range specs {
specs[i] = strings.Trim(s, " ")
}
// filter the environment by the matching variables
m := make(map[string]interface{})
for _, e := range os.Environ() {
pair := strings.Split(e, "=")
if envMatchesPatterns(pair[0], specs) {
m[pair[0]] = pair[1]
}
}
// and return the filtered array
return m
}
// checks if a variables matches a pattern
func envMatchesPatterns(env string, patterns []string) bool {
for _, p := range patterns {
if p != "" {
// if the pattern matches, return true
matched, err := filepath.Match(p, env)
if err == nil && matched {
return true
}
}
}
return false
}
func main() {
// read all the arguments
bindAddress := flag.String("bind", "0.0.0.0:3000", "address to bind to")
envPath := flag.String("path", "/", "server path to serve the resulting json on")
variables := flag.String("vars", "", "comma-seperated list of variables and globs to use")
// parse them
flag.Parse()
// filter the environment and marshal into json
exposed := resolveEnvironment(*variables)
output, err := json.Marshal(exposed)
if err != nil {
log.Fatal(err)
}
// add a handler
http.HandleFunc(*envPath, func(w http.ResponseWriter, r *http.Request) {
callback := r.FormValue("callback")
if callback != "" {
w.Header().Set("Content-Type", "application/javascript")
fmt.Fprintf(w, "%s(%s)", callback, output)
} else {
w.Header().Set("Content-Type", "application/json")
w.Write(output)
}
})
// pretty print what we are going to do
prettyOutput, err := json.MarshalIndent(exposed, "", " ")
if err == nil {
fmt.Printf("Exposing %s ", prettyOutput)
}
fmt.Printf("on '%s', at path '%s'\n", *bindAddress, *envPath)
// and bind
http.ListenAndServe(*bindAddress, nil)
}