1
0
mirror of synced 2024-11-29 00:25:39 +03:00
mg-transport-api-client-go/v1/request.go

105 lines
2.2 KiB
Go
Raw Normal View History

package v1
import (
"bytes"
"fmt"
2018-12-05 17:14:51 +03:00
"io"
"io/ioutil"
2018-06-20 15:27:46 +03:00
"log"
"net/http"
2019-08-14 14:18:12 +03:00
"strings"
)
2018-07-21 18:56:25 +03:00
var prefix = "/api/transport/v1"
// 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-05 17:14:51 +03:00
func (c *MgClient) PostRequest(url string, parameters io.Reader) ([]byte, int, error) {
return makeRequest(
"POST",
fmt.Sprintf("%s%s%s", c.URL, prefix, url),
2018-12-05 17:14:51 +03:00
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
2018-05-21 17:56:42 +03:00
func (c *MgClient) DeleteRequest(url string, parameters []byte) ([]byte, int, error) {
return makeRequest(
"DELETE",
fmt.Sprintf("%s%s%s", c.URL, prefix, url),
2018-05-21 17:56:42 +03:00
bytes.NewBuffer(parameters),
c,
)
}
2018-12-05 17:14:51 +03:00
func makeRequest(reqType, url string, buf io.Reader, c *MgClient) ([]byte, int, error) {
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-Transport-Token", c.Token)
2018-06-20 15:27:46 +03:00
if c.Debug {
2019-08-14 14:18:12 +03:00
if strings.Index(url, "/files/upload") != -1 {
log.Printf("MG TRANSPORT API Request: %s %s %s [file data]", reqType, url, c.Token)
} else {
log.Printf("MG TRANSPORT API Request: %s %s %s %v", reqType, url, c.Token, buf)
}
2018-06-20 15:27:46 +03:00
}
resp, err := c.httpClient.Do(req)
if err != nil {
return res, 0, err
}
if resp.StatusCode >= http.StatusInternalServerError {
2018-11-08 10:15:27 +03:00
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
}
2018-06-20 15:27:46 +03:00
if c.Debug {
log.Printf("MG TRANSPORT API Response: %s", res)
}
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
}