-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
94 lines (78 loc) · 2.15 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
package main
import (
"fmt"
"net/http"
"os"
"time"
"github.com/fatih/color"
"github.com/gorilla/mux"
"github.com/jessevdk/go-flags"
)
var config = Config{
WriteTimeout: 15000 * time.Millisecond,
ReadTimeout: 15000 * time.Millisecond,
IdleTimeout: 60000 * time.Millisecond,
}
func main() {
color.NoColor = true
_, err := flags.Parse(&config)
if err != nil {
exitWithError(fmt.Sprintf("unable to parse command line flags: %s", err))
}
color.NoColor = config.DisableColor
err = config.LoadStubs()
if err != nil {
exitWithError(fmt.Sprintf("error loading stubs: %s", err))
}
serveStubs()
}
func serveStubs() {
router := mux.NewRouter()
for _, stub := range config.Stubs {
fmt.Println(stub.String())
if config.IsCorsEnabled() && isMissingOptionsMethod(stub.Request.Methods) {
stub.Request.Methods = append(stub.Request.Methods, http.MethodOptions)
}
var route *mux.Route
if stub.Request.Path != "" {
route = router.HandleFunc(stub.Request.Path, StubHandler(stub))
} else {
route = router.PathPrefix(stub.Request.PathPrefix).HandlerFunc(StubHandler(stub))
}
route.Methods(stub.Request.Methods...).
MatcherFunc(QueryMatcher(stub.Request.Query)).
MatcherFunc(HeadersMatcher(stub.Request.Headers))
}
if config.IsCorsEnabled() {
fmt.Printf("Allowing CORS from origin '%s'\n", config.CorsAllowOrigin)
router.Use(mux.CORSMethodMiddleware(router))
router.Use(CORSOriginAndHeadersMiddleware)
}
srv := &http.Server{
Handler: router,
Addr: fmt.Sprintf("0.0.0.0:%d", config.Port),
WriteTimeout: config.WriteTimeout,
ReadTimeout: config.ReadTimeout,
IdleTimeout: config.IdleTimeout,
}
fmt.Printf("Serving %d stubs on port %d\n", len(config.Stubs), config.Port)
err := srv.ListenAndServe()
if err != nil {
exitWithError(fmt.Sprintf("error starting server: %s", err))
}
}
func isMissingOptionsMethod(methods []string) bool {
for _, method := range methods {
if method == http.MethodOptions {
return false
}
}
return true
}
func exitWithError(message string) {
printError(message)
os.Exit(1)
}
func printError(message string) {
_, _ = fmt.Fprint(os.Stderr, color.RedString(message))
}