forked from creamdog/aproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
102 lines (86 loc) · 2.34 KB
/
main.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"github.com/creamdog/aproxy/config"
"github.com/creamdog/aproxy/config/file"
"github.com/creamdog/aproxy/config/s3"
"github.com/creamdog/aproxy/listener"
"github.com/creamdog/aproxy/mappings"
"github.com/creamdog/aproxy/cache"
httppipe "github.com/creamdog/aproxy/pipes/http"
//"log"
"net/http"
"time"
"github.com/creamdog/aproxy/log"
)
var mappingsCollection *mappings.Mappings
var cacheClient cache.CacheClient
const (
defaultConfigFile = "config.json"
)
func main() {
config, err := config.Load(defaultConfigFile)
if err != nil {
log.Fatal(err)
}
c, err := cache.Get(config.Cache)
if err != nil {
log.Fatal(err)
}
cacheClient = c
mappingsCollection = initializeMappings(config)
listeners := initializeListeners(config)
if section, exists := config.MappingRepo["s3"]; exists {
s3.Start(mappingsCollection, section.(map[string]interface{}))
} else {
file.Start(mappingsCollection, "mapping-configuration")
}
for listeners.IsRunning() {
time.Sleep(1 * time.Second)
}
}
func ondata(data map[string]interface{}, w http.ResponseWriter) {
mappings := mappingsCollection.Get()
//log.Printf("mappings: %d, data: %v", len(*mappings), data)
if requestMapping, err := mappings.GetMatch(data); err != nil {
log.Print(err)
http.Error(w, err.Error(), 500)
} else if requestMapping != nil {
log.Printf("executing mapping: %v", requestMapping.Id)
pipe := httppipe.New(cacheClient)
pipe.Pipe(requestMapping, w)
} else {
http.Error(w, "these are not the droids you're looking for", 404)
log.Printf("found no mapping matching request")
}
}
type Listeners []listener.Listener
func (col Listeners) IsRunning() bool {
for _, l := range col {
if l.IsRunning() {
return true
}
}
return false
}
func initializeMappings(config *config.Config) *mappings.Mappings {
mapping, err := mappings.Load(config.Mappings)
if err != nil {
log.Fatal(err)
}
return mapping
}
func initializeListeners(config *config.Config) Listeners {
listeners := make([]listener.Listener, 0)
for _, lconfig := range config.Listeners {
if lconfig["type"] == nil {
log.Fatalf("listener type property not set: %v", lconfig)
}
listener, err := listener.Implementations[lconfig["type"].(string)](lconfig, ondata)
if err != nil {
log.Fatal(err)
}
listeners = append(listeners, listener)
listener.Start()
}
return listeners
}