Skip to content

Commit

Permalink
minor fix
Browse files Browse the repository at this point in the history
  • Loading branch information
lucaslopezf committed Apr 18, 2024
1 parent b1000d7 commit a37a845
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
31 changes: 30 additions & 1 deletion pkg/zrouter/zmiddlewares/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ package zmiddlewares

import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"github.com/go-chi/chi/v5"
"github.com/zondax/golem/pkg/logger"
"io"
"net/http"
"regexp"
Expand Down Expand Up @@ -50,7 +52,34 @@ func GetSubRoutePattern(r *http.Request) string {
return undefinedPath
}

return rctx.RoutePattern()
routePattern := rctx.RoutePattern()
if strings.Contains(rctx.RoutePattern(), "*") {
return routePattern
}

return getRoutePrefix(r.Context(), routePattern)
}

func getRoutePrefix(ctx context.Context, route string) string {
if !strings.HasPrefix(route, "/") {
route = "/" + route
}

segments := strings.Split(route, "/")

// The first segment is empty due to the leading "/", so we check the second segment
if len(segments) > 2 {
// The first real segment is at index 1, return it with "/*"
return "/" + segments[1] + "/*"
}

if len(segments) == 2 && segments[1] != "" {
// There's only one segment in the route, return it with "/*"
return "/" + segments[1] + "/*"
}

logger.GetLoggerFromContext(ctx).Errorf("Cannot detect the route prefix for %s", route)
return "/*"
}

func getRequestBody(r *http.Request) ([]byte, error) {
Expand Down
25 changes: 25 additions & 0 deletions pkg/zrouter/zmiddlewares/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package zmiddlewares

import (
"bytes"
"context"
"github.com/go-chi/chi/v5"
"github.com/stretchr/testify/assert"
"io"
Expand Down Expand Up @@ -73,3 +74,27 @@ func TestGenerateBodyHash(t *testing.T) {
hash := generateBodyHash([]byte(testContent))
assert.Equal(t, expectedHash, hash)
}

func TestGetRoutePrefix(t *testing.T) {
tests := []struct {
route string
wantPrefix string
}{
{"/transactions/erc20/{address}", "/transactions/*"},
{"transactions/adasd", "/transactions/*"},
{"/account/12345", "/account/*"},
{"/address/something/else", "/address/*"},
{"dynamic-config", "/dynamic-config/*"},
{"/search/this/item", "/search/*"},
{"/stats", "/stats/*"},
{"/tipset/0", "/tipset/*"},
{"/tools/convert", "/tools/*"},
}

for _, test := range tests {
got := getRoutePrefix(context.Background(), test.route)
if got != test.wantPrefix {
t.Errorf("getRoutePrefix(%q) = %q, want %q", test.route, got, test.wantPrefix)
}
}
}

0 comments on commit a37a845

Please sign in to comment.