Skip to content

Commit

Permalink
update router
Browse files Browse the repository at this point in the history
  • Loading branch information
gaellm committed Jul 21, 2023
1 parent 37afff6 commit c89756c
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 9 deletions.
15 changes: 13 additions & 2 deletions internal/mock/mockBuilder.go
Expand Up @@ -24,6 +24,7 @@ import (
"context"
"encoding/json"
"os"
"strings"

"go.uber.org/zap"
)
Expand Down Expand Up @@ -79,14 +80,24 @@ func BuildMockFromJson(jsonData []byte) (Mock, error) {
} else if h.Type == helper.RANDOM {
mock.AddRandomHelper(h)
} else if h.Type == helper.PATH_REGEX {

mock.AddPathRegexHelper(h)
mock.SetRegexUrl()
}

log.Debug(context.Background(), "helper "+h.Name+" found :'"+h.Target+"'"+" of type : '"+h.Type+"'", zap.String("mock-name", mock.GetName()))
}

//Add / if not present
if mock.Request.Url != "" && !strings.HasPrefix(mock.Request.Url, "/") {
mock.Request.Url = "/" + mock.Request.Url
}
if mock.Request.UrlRegexStr != "" && !strings.HasPrefix(mock.Request.UrlRegexStr, "/") {
mock.Request.UrlRegexStr = "/" + mock.Request.UrlRegexStr
}

if mock.Request.UrlRegexStr != "" {
mock.SetRegexUrl()
}

return mock, nil
}

Expand Down
2 changes: 1 addition & 1 deletion internal/server/mockRoutesBuilder.go
Expand Up @@ -46,7 +46,7 @@ func AddMocksRoutes(mux *http.ServeMux, mockCollection mock.MockCollection, func

log.Debug(ctx, "Creating route for mock '"+m.GetName()+"'", zap.String("mock-url", m.GetRequestUrl()), zap.String("mock-conf", string(m.GetJsonBytes())))

mux.HandleFunc(m.GetRequestUrl(), func(w http.ResponseWriter, r *http.Request) {
mux.HandleFunc("/"+m.GetRequestMethod()+m.GetRequestUrl(), func(w http.ResponseWriter, r *http.Request) {

requestRecover(w, r)
ctx := r.Context()
Expand Down
36 changes: 31 additions & 5 deletions internal/server/server.go
Expand Up @@ -32,6 +32,7 @@ import (
"net"
"net/http"
"strconv"
"strings"
"sync"
"time"

Expand Down Expand Up @@ -93,6 +94,28 @@ func pathHelperMiddleware(mockCollection mock.MockCollection) func(http.Handler)
}
}

func routerMiddleware(next http.Handler) http.Handler {

fn := func(w http.ResponseWriter, r *http.Request) {

r.URL.Path = "/" + r.Method + r.URL.Path

// call next handler
next.ServeHTTP(w, r)

}
return http.HandlerFunc(fn)

}

func removeFirstFolder(path string) string {
components := strings.SplitN(path, "/", 3)
if len(components) >= 3 {
return "/" + components[2]
}
return path
}

// Middleware for logging each request
func logRequestMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand All @@ -102,7 +125,7 @@ func logRequestMiddleware(next http.Handler) http.Handler {
next.ServeHTTP(w, r)

var path string
values := r.Context().Value("pathHelperValues")
values := r.Context().Value(helper.PathHelperKey("pathHelperValues"))
if values != nil {

path = values.(map[string]string)["originalPath"]
Expand All @@ -112,7 +135,7 @@ func logRequestMiddleware(next http.Handler) http.Handler {
}

// Log the request
msg := " " + r.Method + " " + path + " " + r.RemoteAddr + " " + fmt.Sprint(time.Since(start))
msg := " " + r.Method + " " + removeFirstFolder(path) + " " + r.RemoteAddr + " " + fmt.Sprint(time.Since(start))

log.Info(r.Context(), msg)

Expand All @@ -134,6 +157,9 @@ func BuildServer(conf *conf.Config, asyncRunningJobsCount *sync.WaitGroup, mockC
return nil, err
}

//Router
handler = routerMiddleware(handler)

//logger
handler = logRequestMiddleware(handler)

Expand Down Expand Up @@ -188,7 +214,7 @@ func BuildHandler(conf *conf.Config, asyncRunningJobsCount *sync.WaitGroup, mock

//Add Routes
{
mux.HandleFunc("/logger", ChangingLoggingLevelRuntime)
mux.HandleFunc("/POST"+"/logger", ChangingLoggingLevelRuntime)

mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {

Expand All @@ -200,11 +226,11 @@ func BuildHandler(conf *conf.Config, asyncRunningJobsCount *sync.WaitGroup, mock

})

mux.HandleFunc("/alfred", func(w http.ResponseWriter, r *http.Request) {
mux.HandleFunc("/PATCH"+"/alfred", func(w http.ResponseWriter, r *http.Request) {
PatchMock(w, r, mocks)
})

mux.HandleFunc("/alfred/delay", func(w http.ResponseWriter, r *http.Request) {
mux.HandleFunc("/POST"+"/alfred/delay", func(w http.ResponseWriter, r *http.Request) {
DelayMocks(&alfredGlobalDelay, w, r)
})

Expand Down
2 changes: 1 addition & 1 deletion user-files/mocks/examples/helpers/date-helpers.json
Expand Up @@ -6,7 +6,7 @@
},
"response": {
"status": 200,
"body": "{\"a-date-4-minutes-after\": \"{{ alfred.time.date(2009,01,03,4,2,0,3).format('Mon Jan 2 15:04:05 -0700 MST 2006').add('4m') }}\", \"a-date-4-minutes-before\": \"{{ alfred.time.date(2009,01,03,4,2,0,3).format('Mon Jan 2 15:04:05 -0700 MST 2006').add('-4m') }}\",\"a-date-with unix format\": \"{{ alfred.time.date(2009,01,03,4,2,0,3).format('unix') }}\",\"now UTC\": \"{{ alfred.time.now.utc }}\",\"now\": \"{{ alfred.time.now }}\"}",
"body": {"a-date-4-minutes-after": "{{ alfred.time.date(2009,01,03,4,2,0,3).format('Mon Jan 2 15:04:05 -0700 MST 2006').add('4m') }}", "a-date-4-minutes-before": "{{ alfred.time.date(2009,01,03,4,2,0,3).format('Mon Jan 2 15:04:05 -0700 MST 2006').add('-4m') }}","a-date-with unix format": "{{ alfred.time.date(2009,01,03,4,2,0,3).format('unix') }}","now UTC": "{{ alfred.time.now.utc }}","now": "{{ alfred.time.now }}"},
"headers": {
"Content-Type": "application/json"
}
Expand Down

0 comments on commit c89756c

Please sign in to comment.