🔨 Refactor of request method for safe use

Use path if needed, killed Printf, make request URL by url.URL
This commit is contained in:
Maxim Lebedev 2017-12-13 14:59:33 +05:00
parent 21c48af1de
commit 7d9e3b38ae
No known key found for this signature in database
GPG Key ID: F8978F46FF0FFA4F
2 changed files with 49 additions and 37 deletions

49
request.go Normal file
View File

@ -0,0 +1,49 @@
package telegraph
import (
gojson "encoding/json"
"errors"
"fmt"
"net/url"
json "github.com/pquerna/ffjson/ffjson"
http "github.com/valyala/fasthttp"
)
// Response represents a response from the Telegram API with the result stored raw. If ok equals true,
// the request was successful, and the result of the query can be found in the result field. In case of
// an unsuccessful request, ok equals false, and the error is explained in the error field (e.g.
// SHORT_NAME_REQUIRED).
type Response struct {
Ok bool `json:"ok"`
Error string `json:"error"`
Result *gojson.RawMessage `json:"result"`
}
func request(method, path string, args *http.Args) (*Response, error) {
requestURI := &url.URL{
Scheme: "https",
Host: "api.telegra.ph",
Path: method,
}
if path != "" {
requestURI.Path += fmt.Sprint("/", path)
}
_, body, err := http.Post(nil, requestURI.String(), args)
if err != nil {
return nil, err
}
var resp Response
if err := json.Unmarshal(body, &resp); err != nil {
return nil, err
}
if !resp.Ok {
return nil, errors.New(resp.Error)
}
return &resp, nil
}

View File

@ -1,37 +0,0 @@
// Package telegraph has functions and types used for interacting with the
// Telegraph API.
package telegraph
import (
"errors"
json "github.com/pquerna/ffjson/ffjson"
http "github.com/valyala/fasthttp"
)
const (
// APIEndpoint should be presented in this for all queries to the Telegraph
// API must be served over HTTPS.
APIEndpoint = "https://api.telegra.ph/%s"
// PathEndpoint used if a path parameter is present.
PathEndpoint = "https://api.telegra.ph/%s/%s"
)
func request(url string, args *http.Args) (*Response, error) {
_, body, err := http.Post(nil, url, args)
if err != nil {
return nil, err
}
var resp Response
if err := json.Unmarshal(body, &resp); err != nil {
return nil, err
}
if !resp.Ok {
return nil, errors.New(resp.Error)
}
return &resp, nil
}