2015-03-30 14:23:30 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
2016-06-23 12:29:44 +00:00
|
|
|
"encoding/json"
|
2015-06-06 18:15:43 +00:00
|
|
|
"fmt"
|
2015-03-30 14:23:30 +00:00
|
|
|
"io/ioutil"
|
2015-06-23 11:23:39 +00:00
|
|
|
"log"
|
2015-03-30 14:23:30 +00:00
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/bitly/go-simplejson"
|
|
|
|
)
|
|
|
|
|
|
|
|
func Request(req *http.Request) (*simplejson.Json, error) {
|
2015-05-21 03:23:48 +00:00
|
|
|
resp, err := http.DefaultClient.Do(req)
|
2015-03-30 14:23:30 +00:00
|
|
|
if err != nil {
|
2015-06-23 11:23:39 +00:00
|
|
|
log.Printf("%s %s %s", req.Method, req.URL, err)
|
2015-03-30 14:23:30 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
body, err := ioutil.ReadAll(resp.Body)
|
|
|
|
resp.Body.Close()
|
2015-06-23 11:23:39 +00:00
|
|
|
log.Printf("%d %s %s %s", resp.StatusCode, req.Method, req.URL, body)
|
2015-03-30 14:23:30 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if resp.StatusCode != 200 {
|
2015-06-06 18:15:43 +00:00
|
|
|
return nil, fmt.Errorf("got %d %s", resp.StatusCode, body)
|
2015-03-30 14:23:30 +00:00
|
|
|
}
|
|
|
|
data, err := simplejson.NewJson(body)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return data, nil
|
|
|
|
}
|
2015-05-13 01:48:13 +00:00
|
|
|
|
2016-06-23 12:29:44 +00:00
|
|
|
func RequestJson(req *http.Request, v interface{}) error {
|
|
|
|
resp, err := http.DefaultClient.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("%s %s %s", req.Method, req.URL, err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
body, err := ioutil.ReadAll(resp.Body)
|
|
|
|
resp.Body.Close()
|
|
|
|
log.Printf("%d %s %s %s", resp.StatusCode, req.Method, req.URL, body)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if resp.StatusCode != 200 {
|
|
|
|
return fmt.Errorf("got %d %s", resp.StatusCode, body)
|
|
|
|
}
|
|
|
|
return json.Unmarshal(body, v)
|
|
|
|
}
|
|
|
|
|
2015-06-06 18:15:43 +00:00
|
|
|
func RequestUnparsedResponse(url string, header http.Header) (resp *http.Response, err error) {
|
2015-05-13 01:48:13 +00:00
|
|
|
req, err := http.NewRequest("GET", url, nil)
|
|
|
|
if err != nil {
|
2015-06-06 18:15:43 +00:00
|
|
|
return nil, err
|
2015-05-13 01:48:13 +00:00
|
|
|
}
|
|
|
|
req.Header = header
|
|
|
|
|
2015-06-06 18:15:43 +00:00
|
|
|
return http.DefaultClient.Do(req)
|
2015-05-13 01:48:13 +00:00
|
|
|
}
|