Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merge changes from dev to main adding FetchWithContext. #26

Merged
merged 3 commits into from
Dec 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 24 additions & 4 deletions jokeapi.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package jokeapi

import (
"context"
"encoding/json"
"errors"
"fmt"
Expand Down Expand Up @@ -54,8 +55,8 @@ func contextifyError(context string, err error) error {
return fmt.Errorf("%s: %w", context, err)
}

// Fetch gets the content with respect to the parameters
func (j *JokeAPI) Fetch() (JokesResp, error) {
// FetchWithContext gets the content with respect to the parameters. Accepts a context.Context.
func (j *JokeAPI) FetchWithContext(ctx context.Context) (JokesResp, error) {

var (
//response = map[string]interface{}{}
Expand Down Expand Up @@ -89,8 +90,20 @@ func (j *JokeAPI) Fetch() (JokesResp, error) {

reqUrl.RawQuery = query.Encode()

//param handling ends here
resp, err := http.Get(reqUrl.String())
// param handling ends here

// create client
client := &http.Client{}

// create request
req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqUrl.String(), nil)
if err != nil {

return JokesResp{}, err

}

resp, err := client.Do(req)
if err != nil {
return JokesResp{}, contextifyError("Request failed", err)
}
Expand Down Expand Up @@ -132,6 +145,13 @@ func (j *JokeAPI) Fetch() (JokesResp, error) {
}, nil
}

// Fetch gets the content with respect to the parameters. Use FetchWithContext to add your custom context.
func (j *JokeAPI) Fetch() (JokesResp, error) {

return j.FetchWithContext(context.TODO())

}

// SetParams sets parameters to JokeAPI struct instance. This method only exists because I don't want to make breaking changes to the existing api by removing it. I would recommend using Jokeapi{}.Set() or the singular methods instead
func (j *JokeAPI) SetParams(ctgs []string, blacklist []string, joketype string, lang string) {

Expand Down
13 changes: 13 additions & 0 deletions jokeapi_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package jokeapi

import (
"context"
"testing"
)

Expand All @@ -11,6 +12,18 @@ const (
WRONG_CATEGORY = "category not set properly"
)

func Test_Fetch_Context(t *testing.T) {

api := New()
_, err := api.FetchWithContext(context.Background())

if err != nil {

t.Fatal(err)

}
}

func Test_Fetch_Parts(t *testing.T) {

api := New()
Expand Down
Loading