Skip to content

Commit

Permalink
Merge pull request #2 from zry98/master
Browse files Browse the repository at this point in the history
Fix InvokeRequest
  • Loading branch information
celestix authored Dec 3, 2022
2 parents 055ea72 + e258ff6 commit e88e77a
Showing 1 changed file with 6 additions and 7 deletions.
13 changes: 6 additions & 7 deletions requests.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,34 +5,33 @@ import (
"fmt"
"net/http"
"net/url"
"strings"
)

type Body struct {
// Ok: if true, request was successful, and result can be found in the Result field.
// If false, error can be explained in Error field.
Ok bool `json:"ok"`
// Error: contains a human readable description of the error result.
// Error: contains a human-readable description of the error result.
Error string `json:"error"`
// Result: result of requests (if Ok)
Result json.RawMessage `json:"result"`
}

func InvokeRequest(method string, params url.Values) (json.RawMessage, error) {
r, err := http.NewRequest(http.MethodPost, "https://api.telegra.ph/"+method, nil)
r, err := http.NewRequest(http.MethodPost, "https://api.telegra.ph/"+method, strings.NewReader(params.Encode()))
if err != nil {
return nil, fmt.Errorf("failed to build GET request to %s: %w", method, err)
return nil, fmt.Errorf("failed to build POST request to %s: %w", method, err)
}
r.URL.RawQuery = params.Encode()
resp, err := http.DefaultClient.Do(r)
if err != nil {
return nil, fmt.Errorf("failed to execute GET request to %s: %w", method, err)
return nil, fmt.Errorf("failed to execute POST request to %s: %w", method, err)
}
defer resp.Body.Close()

var b Body

if err = json.NewDecoder(resp.Body).Decode(&b); err != nil {
return nil, fmt.Errorf("failed to decode GET request to %s: %w", method, err)
return nil, fmt.Errorf("failed to parse response from %s: %w", method, err)
}
if !b.Ok {
return nil, fmt.Errorf("failed to %s: %s", method, b.Error)
Expand Down

0 comments on commit e88e77a

Please sign in to comment.