point-tools-go/client.go
2016-03-30 05:04:04 +03:00

74 lines
1.6 KiB
Go

// Package point_tools implements simple Point Tools API wrapper for sending some service requests.
package point_tools
import (
"bitbucket.org/skobkin/dumb-http-go"
"bitbucket.org/skobkin/point-api-go"
"encoding/json"
"errors"
"log"
"net/http"
"net/url"
)
// Package errors
var (
ErrHttpRequest = errors.New("point-api: HTTP request error")
ErrJsonDeserialization = errors.New("point-api: JSON deserialization error")
)
type PointToolsClient struct {
client simple_http.Client
apiUrl string
token string
}
// New creates new Point Tools API client instance and initialize it to use provided URL and token
func New(apiUrl, token string) PointToolsClient {
return PointToolsClient{
simple_http.Client{http.Client{}},
apiUrl,
token,
}
}
func GetPageJSON(page point.Page) (string, error) {
b, err := json.Marshal(page)
if err != nil {
log.Println("point.Page serialize error:", err)
return "", err
}
return string(b[:]), nil
}
// SendAllPage sends /all page to Point Tools crawler API gate for processing
func (c *PointToolsClient) SendAllPage(page point.Page) (SendAllPageResponse, error) {
var response SendAllPageResponse
jsonStr, err := GetPageJSON(page)
if err != nil {
return response, err
}
data := url.Values{}
data.Set("token", c.token)
data.Add("json", jsonStr)
body, reqErr := c.client.MakePostRequest(c.apiUrl+"all/page", data, nil)
if reqErr != nil {
return response, ErrHttpRequest
}
jsonErr := json.Unmarshal(body, &response)
if jsonErr != nil {
return response, ErrJsonDeserialization
}
return response, nil
}