Skip to content

Commit

Permalink
Merge pull request #26 from Icelain/dev
Browse files Browse the repository at this point in the history
Merge changes from dev to main adding FetchWithContext.
  • Loading branch information
Icelain authored Dec 30, 2023
2 parents 0e077dc + e43be7e commit 6b33385
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
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

0 comments on commit 6b33385

Please sign in to comment.