From 31b93d709da7ab4d572e5e48df04c203427c41e1 Mon Sep 17 00:00:00 2001 From: Lucas TESSON Date: Sun, 10 Dec 2023 09:38:28 +0100 Subject: [PATCH] feat: add support of functional options to file content download --- api/client.go | 14 +++++++++++--- api/files.go | 3 ++- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/api/client.go b/api/client.go index c978bca..a94fad5 100644 --- a/api/client.go +++ b/api/client.go @@ -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 { diff --git a/api/files.go b/api/files.go index 98b6587..40a20b1 100644 --- a/api/files.go +++ b/api/files.go @@ -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