Skip to content

Commit

Permalink
Request: add ability to change request context
Browse files Browse the repository at this point in the history
  • Loading branch information
System-Glitch committed Oct 9, 2023
1 parent 5aa1f46 commit fa818d7
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
20 changes: 20 additions & 0 deletions request.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package goyave

import (
"context"
"io"
"net/http"
"net/url"
Expand Down Expand Up @@ -157,3 +158,22 @@ func (r *Request) BearerToken() (string, bool) {
func (r *Request) Body() io.ReadCloser {
return r.httpRequest.Body
}

// Context returns the request's context. To change the context, use `WithContext`.
//
// The returned context is always non-nil; it defaults to the
// background context.
//
// The context is canceled when the client's connection closes, the request is canceled (with HTTP/2),
// or when the `ServeHTTP` method returns (after the finalization step of the request lifecycle).
func (r *Request) Context() context.Context {
return r.httpRequest.Context()
}

// WithContext creates a shallow copy of the underlying `*http.Request` with
// its context changed to `ctx` then returns itself.
// The provided ctx must be non-nil.
func (r *Request) WithContext(ctx context.Context) *Request {
r.httpRequest = r.httpRequest.WithContext(ctx)
return r
}
19 changes: 19 additions & 0 deletions request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package goyave

import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"testing"
Expand Down Expand Up @@ -72,4 +73,22 @@ func TestRequest(t *testing.T) {
assert.Empty(t, token)
assert.False(t, ok)
})

t.Run("Context", func(t *testing.T) {
httpReq := httptest.NewRequest(http.MethodGet, "/test", nil)
r := NewRequest(httpReq)

ctx := r.Context()
if !assert.NotNil(t, ctx) {
return
}
assert.Equal(t, httpReq.Context(), ctx)

key := struct{}{}
r2 := r.WithContext(context.WithValue(ctx, key, "value"))
assert.Equal(t, r, r2)

ctx2 := r.Context()
assert.Equal(t, "value", ctx2.Value(key))
})
}

0 comments on commit fa818d7

Please sign in to comment.