25 ErrEntityNotFound = errors.New("entity not found") |
29 ErrEntityNotFound = errors.New("entity not found") |
26 ErrInvalidParameter = errors.New("incorrect parameter") |
30 ErrInvalidParameter = errors.New("incorrect parameter") |
27 ErrInvalidID = errors.New("incorrect entity ID") |
31 ErrInvalidID = errors.New("incorrect entity ID") |
28 ) |
32 ) |
29 |
33 |
30 // prepareRequest insert all pre-defined stuff |
34 // prepareRequest inserts all pre-defined stuff |
31 func (g *Client) prepareRequest(what string) (req rest.Request) { |
35 func (g *Client) prepareRequest(target string, method rest.Method, params apiCallParams) (req rest.Request) { |
32 var endPoint string |
36 endPoint := g.APIBase + "/" + target |
33 |
37 |
34 endPoint = g.APIBase + "/" + what |
38 // Request headers |
35 // Add at least one option, the APIkey if present |
|
36 hdrs := make(map[string]string) |
39 hdrs := make(map[string]string) |
37 opts := make(map[string]string) |
|
38 |
|
39 // Insert our sig |
|
40 hdrs["User-Agent"] = fmt.Sprintf("Gondole/%s", GondoleVersion) |
40 hdrs["User-Agent"] = fmt.Sprintf("Gondole/%s", GondoleVersion) |
41 if g.userToken != nil { |
41 if g.userToken != nil { |
42 hdrs["Authorization"] = fmt.Sprintf("Bearer %s", g.userToken.AccessToken) |
42 hdrs["Authorization"] = fmt.Sprintf("Bearer %s", g.userToken.AccessToken) |
43 } |
43 } |
44 |
44 |
45 req = rest.Request{ |
45 req = rest.Request{ |
46 BaseURL: endPoint, |
46 BaseURL: endPoint, |
47 Headers: hdrs, |
47 Headers: hdrs, |
48 QueryParams: opts, |
48 Method: method, |
|
49 QueryParams: params, |
49 } |
50 } |
50 return |
51 return |
51 } |
52 } |
|
53 |
|
54 // apiCall makes a call to the Mastodon API server |
|
55 func (g *Client) apiCall(endPoint string, method rest.Method, params apiCallParams, data interface{}) error { |
|
56 // Prepare query |
|
57 req := g.prepareRequest(endPoint, method, params) |
|
58 |
|
59 // Make API call |
|
60 r, err := rest.API(req) |
|
61 if err != nil { |
|
62 return fmt.Errorf("API query (%s) failed: %s", endPoint, err.Error()) |
|
63 } |
|
64 |
|
65 // Check for error reply |
|
66 var errorResult Error |
|
67 if err := json.Unmarshal([]byte(r.Body), &errorResult); err == nil { |
|
68 // The empty object is not an error |
|
69 if errorResult.Text != "" { |
|
70 return fmt.Errorf("%s", errorResult.Text) |
|
71 } |
|
72 } |
|
73 |
|
74 // Not an error reply; let's unmarshal the data |
|
75 err = json.Unmarshal([]byte(r.Body), &data) |
|
76 if err != nil { |
|
77 return fmt.Errorf("cannot decode API response (%s): %s", method, err.Error()) |
|
78 } |
|
79 return nil |
|
80 } |