Skip to content

Commit

Permalink
feat(ctx): add Context management to RequestConfig struct
Browse files Browse the repository at this point in the history
- Add a Context field to the RequestConfig struct
- Initialize the Context field with a default value in the New function
- Implement a SetContext method to update the Context field
- Update the initTest function to use the RequestConfig's Context instead of a new background context

Signed-off-by: appleboy <appleboy.tw@gmail.com>
  • Loading branch information
appleboy committed Nov 2, 2024
1 parent e8ffcc8 commit 89bceeb
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions gofight.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ type RequestConfig struct {
Cookies H
Debug bool
ContentType string
Context context.Context
}

// UploadFile for upload file struct
Expand All @@ -107,7 +108,9 @@ type UploadFile struct {

// New supply initial structure
func New() *RequestConfig {
return &RequestConfig{}
return &RequestConfig{
Context: context.Background(),
}
}

// SetDebug supply enable debug mode.
Expand All @@ -117,6 +120,23 @@ func (rc *RequestConfig) SetDebug(enable bool) *RequestConfig {
return rc
}

// SetContext sets the context for the RequestConfig.
// This allows the request to be aware of deadlines, cancellation signals, and other request-scoped values.
// It returns the updated RequestConfig instance.
//
// Parameters:
//
// ctx - the context to be set for the RequestConfig
//
// Returns:
//
// *RequestConfig - the updated RequestConfig instance with the new context
func (rc *RequestConfig) SetContext(ctx context.Context) *RequestConfig {
rc.Context = ctx

return rc
}

// GET is request method.
func (rc *RequestConfig) GET(path string) *RequestConfig {
rc.Path = path
Expand Down Expand Up @@ -338,7 +358,7 @@ func (rc *RequestConfig) initTest() (*http.Request, *httptest.ResponseRecorder)

body := bytes.NewBufferString(rc.Body)

req, _ := http.NewRequestWithContext(context.Background(), rc.Method, rc.Path, body)
req, _ := http.NewRequestWithContext(rc.Context, rc.Method, rc.Path, body)
req.RequestURI = req.URL.RequestURI()

if len(qs) > 0 {
Expand Down

0 comments on commit 89bceeb

Please sign in to comment.