Skip to content

Commit

Permalink
Build routes dynamically based on mappings
Browse files Browse the repository at this point in the history
  • Loading branch information
enginyoyen committed Mar 30, 2021
1 parent 5cddf4e commit 78fb314
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 24 deletions.
1 change: 0 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,5 @@ func main() {
}

mappings := mapping.MapRequests(files)

server.Serve(config, mappings)
}
6 changes: 4 additions & 2 deletions pkg/mapping/mapping.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"io/ioutil"
"os"
"time"
)

type Mapping struct {
Expand All @@ -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 {
Expand Down
37 changes: 16 additions & 21 deletions pkg/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"log"
"net/http"
"strconv"
"strings"
"time"

"github.com/enginyoyen/mimic/pkg/cmd"
Expand All @@ -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{
Expand All @@ -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
}

0 comments on commit 78fb314

Please sign in to comment.