From 7d9e3b38aea999ae77955c3128f3e5880a6e5d7d Mon Sep 17 00:00:00 2001 From: Maxim Lebedev Date: Wed, 13 Dec 2017 14:59:33 +0500 Subject: [PATCH] :hammer: Refactor of request method for safe use Use path if needed, killed Printf, make request URL by url.URL --- request.go | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ telegraph.go | 37 ------------------------------------- 2 files changed, 49 insertions(+), 37 deletions(-) create mode 100644 request.go delete mode 100644 telegraph.go diff --git a/request.go b/request.go new file mode 100644 index 0000000..d99fcda --- /dev/null +++ b/request.go @@ -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 +} diff --git a/telegraph.go b/telegraph.go deleted file mode 100644 index 201a1e5..0000000 --- a/telegraph.go +++ /dev/null @@ -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 -}