Skip to content

Commit

Permalink
Add router endpoint pattern method onto the Typhon Request
Browse files Browse the repository at this point in the history
  • Loading branch information
RohanPadmanabhan committed Dec 1, 2023
1 parent ea17ae8 commit 84a107d
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
18 changes: 17 additions & 1 deletion request.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ func (r *Request) BodyBytes(consume bool) ([]byte, error) {
// Send round-trips the request via the default Client. It does not block, instead returning a ResponseFuture
// representing the asynchronous operation to produce the response. It is equivalent to:
//
// r.SendVia(Client)
// r.SendVia(Client)
func (r Request) Send() *ResponseFuture {
return Send(r)
}
Expand Down Expand Up @@ -213,6 +213,22 @@ func (r Request) ResponseWithCode(body interface{}, statusCode int) Response {
return rsp
}

// RouterEndpointPattern finds the router pattern that matches the request. This is only callable while the request
// is being served.
func (r Request) RouterEndpointPattern() string {
if router := RouterForRequest(r); router != nil {
if pathPattern := router.Pattern(r); pathPattern != "" {
return pathPattern
}
}
return ""
}

// RequestMethod returns the HTTP method of the request
func (r Request) RequestMethod() string {
return r.Method
}

func (r Request) String() string {
if r.URL == nil {
return "Request(Unknown)"
Expand Down
22 changes: 22 additions & 0 deletions request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"encoding/json"
"io/ioutil"
"math"
"net/http"
"strings"
"testing"

Expand Down Expand Up @@ -223,6 +224,27 @@ func TestRequestSetMetadata(t *testing.T) {
assert.Equal(t, []string{"data"}, req.Request.Header["meta"])
}

func TestRouterEndpointPattern(t *testing.T) {
req := NewRequest(context.Background(), http.MethodGet, "/foo/some-url-identifier", nil)
assert.Equal(t, "", req.RouterEndpointPattern()) // should be empty if request has not been served by a router

router := Router{}
routerEndpointPattern := "/foo/:id"
router.GET(routerEndpointPattern, func(req Request) Response {
// as we are currently serving the request, we should be able to get the router endpoint pattern
assert.Equal(t, routerEndpointPattern, req.RouterEndpointPattern())
return req.Response(nil)
})

rsp := req.SendVia(router.Serve()).Response()
require.NoError(t, rsp.Error) // check we didn't get a "route not found" error
}

func TestRequestMethod(t *testing.T) {
req := NewRequest(context.Background(), http.MethodGet, "", nil)
assert.Equal(t, http.MethodGet, req.RequestMethod())
}

func jsonStreamMarshal(v interface{}) ([]byte, error) {
var buffer bytes.Buffer
writer := bufio.NewWriter(&buffer)
Expand Down

0 comments on commit 84a107d

Please sign in to comment.