mg-bot-api-client-go/v1/request.go

109 lines
2.2 KiB
Go
Raw Permalink Normal View History

2018-08-03 18:11:37 +03:00
package v1
import (
"bytes"
"fmt"
2018-12-26 17:38:41 +03:00
"io"
2018-08-03 18:11:37 +03:00
"io/ioutil"
"net/http"
)
2018-08-29 02:44:06 +03:00
var prefix = "/api/bot/v1"
2018-08-03 18:11:37 +03:00
// GetRequest implements GET Request
func (c *MgClient) GetRequest(url string, parameters []byte) ([]byte, int, error) {
return makeRequest(
"GET",
fmt.Sprintf("%s%s%s", c.URL, prefix, url),
bytes.NewBuffer(parameters),
c,
)
}
// PostRequest implements POST Request
2018-12-26 17:38:41 +03:00
func (c *MgClient) PostRequest(url string, parameters io.Reader) ([]byte, int, error) {
2018-08-03 18:11:37 +03:00
return makeRequest(
"POST",
fmt.Sprintf("%s%s%s", c.URL, prefix, url),
2018-12-26 17:38:41 +03:00
parameters,
2018-08-03 18:11:37 +03:00
c,
)
}
// PatchRequest implements PATCH Request
func (c *MgClient) PatchRequest(url string, parameters []byte) ([]byte, int, error) {
return makeRequest(
"PATCH",
fmt.Sprintf("%s%s%s", c.URL, prefix, url),
bytes.NewBuffer(parameters),
c,
)
}
// PutRequest implements PUT Request
func (c *MgClient) PutRequest(url string, parameters []byte) ([]byte, int, error) {
return makeRequest(
"PUT",
fmt.Sprintf("%s%s%s", c.URL, prefix, url),
bytes.NewBuffer(parameters),
c,
)
}
// DeleteRequest implements DELETE Request
func (c *MgClient) DeleteRequest(url string, parameters []byte) ([]byte, int, error) {
return makeRequest(
"DELETE",
fmt.Sprintf("%s%s%s", c.URL, prefix, url),
bytes.NewBuffer(parameters),
c,
)
}
2018-12-26 17:38:41 +03:00
func makeRequest(reqType, url string, buf io.Reader, c *MgClient) ([]byte, int, error) {
2018-08-03 18:11:37 +03:00
var res []byte
req, err := http.NewRequest(reqType, url, buf)
if err != nil {
return res, 0, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Bot-Token", c.Token)
if c.Debug {
2021-11-25 12:51:29 +03:00
c.writeLog("MG BOT API Request: %s %s %s %+v", reqType, url, c.Token, buf)
2018-08-03 18:11:37 +03:00
}
resp, err := c.httpClient.Do(req)
if err != nil {
return res, 0, err
}
if resp.StatusCode >= http.StatusInternalServerError {
err = fmt.Errorf("http request error. Status code: %d", resp.StatusCode)
return res, resp.StatusCode, err
}
res, err = buildRawResponse(resp)
if err != nil {
return res, 0, err
}
if c.Debug {
2021-11-25 12:51:29 +03:00
c.writeLog("MG BOT API Response: %s", res)
2018-08-03 18:11:37 +03:00
}
return res, resp.StatusCode, err
}
func buildRawResponse(resp *http.Response) ([]byte, error) {
defer resp.Body.Close()
res, err := ioutil.ReadAll(resp.Body)
if err != nil {
return res, err
}
return res, nil
}