Skip to content

Commit

Permalink
feat: add support of functional options to file content download
Browse files Browse the repository at this point in the history
  • Loading branch information
pandatix committed Dec 10, 2023
1 parent 8345bcb commit 31b93d7
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
14 changes: 11 additions & 3 deletions api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,17 +94,25 @@ func WithContext(ctx context.Context) Option {
}
}

// call is in charge of handling common CTFd API behaviours,
// like dealing with status codes and JSON errors.
func call(client *Client, req *http.Request, dst any, opts ...Option) error {
func applyOpts(req *http.Request, opts ...Option) *http.Request {
reqopts := &options{
Ctx: context.Background(),
}

for _, opt := range opts {
opt.apply(reqopts)
}

req = req.WithContext(reqopts.Ctx)

return req
}

// call is in charge of handling common CTFd API behaviours,
// like dealing with status codes and JSON errors.
func call(client *Client, req *http.Request, dst any, opts ...Option) error {
req = applyOpts(req, opts...)

// Set API base URL
newUrl, err := url.Parse("/api/v1" + req.URL.String())
if err != nil {
Expand Down
3 changes: 2 additions & 1 deletion api/files.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,13 @@ type InputFile struct {

// GetFileContent is a helper leveraging the CTFd API that
// downloads a file's content given its location.
func (client *Client) GetFileContent(file *File) ([]byte, error) {
func (client *Client) GetFileContent(file *File, opts ...Option) ([]byte, error) {
if file == nil {
return nil, errors.New("can't get file from a nil value")
}

req, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("/files/%s", file.Location), nil)
req = applyOpts(req, opts...)
res, err := client.Do(req)
if err != nil {
return nil, err
Expand Down

0 comments on commit 31b93d7

Please sign in to comment.