From 78fb314da081df2ccd775e3d1f493d249ddadc0d Mon Sep 17 00:00:00 2001 From: Engin Yoeyen Date: Tue, 30 Mar 2021 07:30:38 +0200 Subject: [PATCH] Build routes dynamically based on mappings --- main.go | 1 - pkg/mapping/mapping.go | 6 ++++-- pkg/server/server.go | 37 ++++++++++++++++--------------------- 3 files changed, 20 insertions(+), 24 deletions(-) diff --git a/main.go b/main.go index c7e2d5c..e495116 100644 --- a/main.go +++ b/main.go @@ -22,6 +22,5 @@ func main() { } mappings := mapping.MapRequests(files) - server.Serve(config, mappings) } diff --git a/pkg/mapping/mapping.go b/pkg/mapping/mapping.go index 41eabd7..dc490ab 100644 --- a/pkg/mapping/mapping.go +++ b/pkg/mapping/mapping.go @@ -5,6 +5,7 @@ import ( "fmt" "io/ioutil" "os" + "time" ) type Mapping struct { @@ -19,8 +20,9 @@ type Request struct { } type Response struct { - Status int - Body string + Status int + Body json.RawMessage + WithDelay time.Duration } func MapRequests(files *[]string) *[]Mapping { diff --git a/pkg/server/server.go b/pkg/server/server.go index af53003..f14abb8 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -5,6 +5,7 @@ import ( "log" "net/http" "strconv" + "strings" "time" "github.com/enginyoyen/mimic/pkg/cmd" @@ -17,7 +18,21 @@ var mappings *[]mapping.Mapping func Serve(config *cmd.Config, maps *[]mapping.Mapping) { mappings = maps r := mux.NewRouter() - r.HandleFunc(`/{rest:[a-zA-Z0-9=\-\/]+}`, MockHandler) + r.HandleFunc("/mimic", InitHandler) + + for _, v := range *mappings { + m := v + r.HandleFunc(m.Request.Url, func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(m.Response.Status) + body := string(m.Response.Body) + body = strings.TrimLeft(body, "\"") + body = strings.TrimRight(body, "\"") + fmt.Fprintf(w, "%v", body) + if m.Response.WithDelay > 0 { + time.Sleep(time.Millisecond * m.Response.WithDelay) + } + }).Methods(m.Request.Method) + } addr := config.BindAddress + ":" + strconv.Itoa(config.Port) srv := &http.Server{ @@ -27,29 +42,9 @@ func Serve(config *cmd.Config, maps *[]mapping.Mapping) { ReadTimeout: time.Duration(config.ReadTimeout) * time.Second, } log.Fatal(srv.ListenAndServe()) - } func InitHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) fmt.Fprintf(w, "You are using mimics\n") } - -func MockHandler(w http.ResponseWriter, r *http.Request) { - if m, ok := match(r); ok { - w.WriteHeader(m.Response.Status) - fmt.Fprintf(w, m.Response.Body) - } else { - w.WriteHeader(http.StatusNotFound) - fmt.Fprintf(w, "Not found\n") - } -} - -func match(r *http.Request) (*mapping.Mapping, bool) { - for _, v := range *mappings { - if v.Request.Url == r.URL.Path { - return &v, true - } - } - return nil, false -}