Added error handling if SCG returns non-200 HTTP status code

This commit is contained in:
flygrounder 2020-02-27 10:41:03 +03:00
parent d422f63f9c
commit 33ba48c968
3 changed files with 26 additions and 5 deletions

View file

@ -37,7 +37,9 @@ func GetCardByUrl(path string) string {
if err != nil {
return ""
}
defer response.Body.Close()
defer func() {
_ = response.Body.Close()
}()
data, err := ioutil.ReadAll(response.Body)
if err != nil {
return ""

View file

@ -2,8 +2,10 @@ package cardsinfo
import (
"encoding/json"
"errors"
"github.com/antchfx/htmlquery"
"golang.org/x/net/html"
"golang.org/x/net/html/charset"
"io/ioutil"
"net/http"
"strings"
@ -16,13 +18,31 @@ const MaxCards = 4
func GetSCGPrices(name string) ([]CardPrice, error) {
preprocessedName := preprocessNameForSearch(name)
url := getSCGUrl(preprocessedName)
doc, err := htmlquery.LoadURL(url)
doc, err := getScgHTML(url)
if err != nil {
return nil, err
}
return fetchPrices(doc)
}
func getScgHTML(url string) (*html.Node, error) {
response, err := http.Get(url)
defer func() {
_ = response.Body.Close()
}()
if response.StatusCode != http.StatusOK {
return nil, errors.New("not ok status")
}
r, err := charset.NewReader(response.Body, response.Header.Get("Content-Type"))
if err != nil {
return nil, err
}
return html.Parse(r)
}
func preprocessNameForSearch(name string) string {
return strings.Split(name, "|")[0]
}
@ -119,8 +139,7 @@ func getPriceById(id string) float64 {
}
func getSCGUrl(name string) string {
words := strings.Split(name, " ")
scgName := strings.Join(words, "+")
scgName := strings.Replace(name, " ", "+", -1)
url := Scgurl + scgName
return url
}

View file

@ -20,7 +20,7 @@ func Message(userId int64, message string) {
"peer_id=" + strconv.FormatInt(userId, 10),
"message=" + url.QueryEscape(message),
"v=5.95",
"random_id=" + strconv.FormatInt(int64(randomId), 10),
"random_id=" + strconv.FormatInt(randomId, 10),
}
paramString := strings.Join(params, "&")
resp, err := http.Get(SendMessageUrl + "?" + paramString)