package point import ( "bitbucket.org/skobkin/point-tools-crawler/simple_http" "encoding/json" "errors" "log" "net/http" "net/url" "strconv" ) type PointClient struct { client simple_http.Client apiUrl string token Token } func NewClient(apiUrl string) PointClient { return PointClient{ simple_http.Client{http.Client{}}, apiUrl, Token{}, } } func (c *PointClient) Login(login, password string) (Token, error) { var token Token data := url.Values{} data.Set("login", login) data.Set("password", password) body, req_err := c.client.MakePostRequest(c.apiUrl+"login", data, nil) if req_err != nil { return token, req_err } json_err := json.Unmarshal(body, &token) if json_err != nil { log.Fatal(json_err) return token, errors.New("JSON deserialization error") } if token.Error != "" { return token, errors.New(token.Error) } c.token = token return token, nil } func (c *PointClient) GetRecentAllPostsPage() (Page, error) { var page Page if len(c.token.AuthToken) == 0 { log.Fatal("Can not get recent posts. Login first.") return page, errors.New("Login first") } headers := map[string]string{ "Authorization": c.token.AuthToken, } body, req_err := c.client.MakeGetRequest(c.apiUrl+"all", nil, &headers) if req_err != nil { return page, errors.New("HTTP request error") } json_err := json.Unmarshal(body, &page) if json_err != nil { log.Fatal(json_err) return page, errors.New("JSON deserialization error") } // Move page.Error to response object if page.Error == "NotAuthorized" { log.Fatal("Please use correct login and password to fetch recent posts") return page, errors.New("Not authorized") } return page, nil } func (c *PointClient) GetNextAllPostsPage(page Page) (Page, error) { var nextPage Page if false == page.HasNext || len(page.Posts) == 0 { return nextPage, errors.New("Page must have has_next=true and some posts") } if len(c.token.AuthToken) == 0 { log.Fatal("Can not get recent posts. Login first.") return nextPage, errors.New("Login first") } data := url.Values{} data.Set("before", strconv.Itoa(page.Posts[len(page.Posts)-1].Uid)) headers := map[string]string{ "Authorization": c.token.AuthToken, } body, req_err := c.client.MakeGetRequest(c.apiUrl+"all", &data, &headers) if req_err != nil { return nextPage, errors.New("HTTP request error") } json_err := json.Unmarshal(body, &nextPage) if json_err != nil { log.Fatal(json_err) return nextPage, errors.New("JSON deserialization error") } // Move page.Error to response object if nextPage.Error == "NotAuthorized" { log.Fatal("Please use correct login and password to fetch recent posts") return nextPage, errors.New("Not authorized") } return nextPage, nil }