forked from Arrim/http-api-mock
-
Notifications
You must be signed in to change notification settings - Fork 1
/
http-api-mock.go
183 lines (149 loc) · 5.92 KB
/
http-api-mock.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
package main
import (
"errors"
"flag"
"fmt"
"net"
"path/filepath"
"strings"
"github.com/kolesa-team/http-api-mock/console"
"github.com/kolesa-team/http-api-mock/definition"
"github.com/kolesa-team/http-api-mock/logging"
"github.com/kolesa-team/http-api-mock/match"
"github.com/kolesa-team/http-api-mock/notify"
"github.com/kolesa-team/http-api-mock/persist"
"github.com/kolesa-team/http-api-mock/route"
"github.com/kolesa-team/http-api-mock/server"
"github.com/kolesa-team/http-api-mock/translate"
"github.com/kolesa-team/http-api-mock/utils"
"github.com/kolesa-team/http-api-mock/vars"
"github.com/kolesa-team/http-api-mock/vars/fakedata"
)
//ErrNotFoundDefaultPath if we can't resolve the current path
var ErrNotFoundDefaultPath = errors.New("We can't determinate the current path")
//ErrNotFoundAnyMock when we don't found any valid mock definition to load
var ErrNotFoundAnyMock = errors.New("No valid mock definition found")
func banner() {
fmt.Println("HTTP API Mock v 1.2.1")
fmt.Println("")
fmt.Print(
` .---. .---.
: : o : me want request!
_..-: o : :-.._ /
.-'' ' ` + "`" + `---' ` + "`" + `---' " ` + "`" + `` + "`" + `-.
.' " ' " . " . ' " ` + "`" + `.
: '.---.,,.,...,.,.,.,..---. ' ;
` + "`" + `. " ` + "`" + `. .' " .'
` + "`" + `. '` + "`" + `. .' ' .'
` + "`" + `. ` + "`" + `-._ _.-' " .' .----.
` + "`" + `. " '"--...--"' . ' .' .' o ` + "`" + `.
.'` + "`" + `-._' " . " _.-'` + "`" + `. : o :
.' ` + "`" + `` + "`" + `` + "`" + `--.....--''' ' ` + "`" + `:_ o :
.' " ' " " ; ` + "`" + `.;";";";'
; ' " ' . ; .' ; ; ;
; ' ' ' " .' .-'
' " " ' " " _.-'
`)
fmt.Println("")
}
// Get preferred outbound ip of this machine
func getOutboundIP() string {
conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
return "127.0.0.1"
}
defer conn.Close()
logging.Println("Getting external IP")
localAddr := conn.LocalAddr().String()
idx := strings.LastIndex(localAddr, ":")
return localAddr[0:idx]
}
func getRouter(mocks []definition.Mock, dUpdates chan []definition.Mock) *route.RequestRouter {
logging.Printf("Loding router with %d definitions\n", len(mocks))
router := route.NewRouter(mocks, match.MockMatch{}, dUpdates)
router.MockChangeWatch()
return router
}
func loadVarsProcessorEngines(persistPath string) *persist.PersistEngineBag {
var persister persist.EntityPersister
if strings.Index(persistPath, "mongodb://") < 0 {
persister = persist.NewFilePersister(persistPath)
} else {
persister = persist.NewMongoPersister(persistPath)
}
persistBag := persist.GetNewPersistEngineBag(persister)
return persistBag
}
func getVarsProcessor(persistEngineBag *persist.PersistEngineBag) vars.VarsProcessor {
return vars.VarsProcessor{FillerFactory: vars.MockFillerFactory{}, FakeAdapter: fakedata.FakeAdapter{}, PersistEngines: persistEngineBag}
}
func startServer(ip string, port int, done chan bool, router route.Router, mLog chan definition.Match, varsProcessor vars.VarsProcessor, logs chan string) {
dispatcher := server.Dispatcher{IP: ip,
Port: port,
Router: router,
Translator: translate.HTTPTranslator{},
VarsProcessor: varsProcessor,
Mlog: mLog,
Notifier: notify.NewMockNotifier(),
Logs: logs,
}
dispatcher.Start()
done <- true
}
func startConsole(ip string, port int, done chan bool, mLog chan definition.Match, logs chan string) {
dispatcher := console.Dispatcher{IP: ip, Port: port, Mlog: mLog, Logs: logs}
dispatcher.Start()
done <- true
}
func getMocks(path string, updateCh chan []definition.Mock) []definition.Mock {
logging.Printf("Reading Mock definition from: %s\n", path)
definitionReader := definition.NewFileDefinition(path, updateCh)
definitionReader.AddConfigReader(definition.JSONReader{})
definitionReader.AddConfigReader(definition.YAMLReader{})
mocks := definitionReader.ReadMocksDefinition()
if len(mocks) == 0 {
logging.Fatalln(ErrNotFoundAnyMock.Error())
}
definitionReader.WatchDir()
return mocks
}
func main() {
banner()
outIP := getOutboundIP()
path, err := filepath.Abs("./config")
if err != nil {
panic(ErrNotFoundDefaultPath)
}
persistPath, _ := filepath.Abs("./data")
//persistPath := "mongodb://localhost/http-api-mock"
sIP := flag.String("server-ip", outIP, "Mock server IP")
sPort := flag.Int("server-port", 8083, "Mock Server Port")
cIP := flag.String("console-ip", outIP, "Console Server IP")
cPort := flag.Int("console-port", 8082, "Console server Port")
console := flag.Bool("console", true, "Console enabled (true/false)")
cPath := flag.String("config-path", path, "Mocks definition folder")
cPersistPath := flag.String("config-persist-path", persistPath, "Path to the folder where requests can be persisted or connection string to mongo database starting with mongodb:// and having database at the end /DatabaseName")
flag.Parse()
path, _ = filepath.Abs(*cPath)
if strings.Index(*cPersistPath, "mongodb://") < 0 {
*cPersistPath, _ = filepath.Abs(*cPersistPath)
}
//chanels
mLog := make(chan definition.Match)
logs := make(chan string)
dUpdates := make(chan []definition.Mock)
done := make(chan bool)
mocks := getMocks(path, dUpdates)
router := getRouter(mocks, dUpdates)
persistEngineBag := loadVarsProcessorEngines(*cPersistPath)
varsProcessor := getVarsProcessor(persistEngineBag)
go startServer(*sIP, *sPort, done, router, mLog, varsProcessor, logs)
utils.SetServerAddress(fmt.Sprintf("http://%s:%d", *sIP, *sPort))
logging.Printf("HTTP Server running at %s\n", utils.GetServerAddress())
if *console {
go startConsole(*cIP, *cPort, done, mLog, logs)
logging.Printf("Console running at http://%s:%d\n", *cIP, *cPort)
logging.SetLogger(logging.ChannelLogger{ChannelLog: logs})
}
<-done
}