fsdfsd
commit
e4b9073ff7
|
@ -0,0 +1,76 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type APIClient struct {
|
||||
baseURL string
|
||||
apiKey string
|
||||
}
|
||||
|
||||
func NewAPIClient(baseURL, apiKey string) *APIClient {
|
||||
return &APIClient{
|
||||
baseURL: baseURL,
|
||||
apiKey: apiKey,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *APIClient) makeRequest(method, path string, v interface{}) error {
|
||||
url := c.baseURL + path
|
||||
req, err := http.NewRequest(method, url, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", c.apiKey))
|
||||
|
||||
client := http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
|
||||
return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
return json.NewDecoder(resp.Body).Decode(v)
|
||||
}
|
||||
|
||||
type CommentResponse struct {
|
||||
Data []Comment `json:"data"`
|
||||
}
|
||||
|
||||
type Comment struct {
|
||||
ID int `json:"id"`
|
||||
Author string `json:"author"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
func (c *APIClient) GetComments() ([]Comment, error) {
|
||||
var comments CommentResponse
|
||||
if err := c.makeRequest("GET", "/comments", &comments); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return comments.Data, nil
|
||||
}
|
||||
|
||||
func (c *APIClient) MakeComment(author, text string) error {
|
||||
body := bytes.NewBuffer([]byte(fmt.Sprintf(`{"author": "%s", "text": "%s"}`, author, text)))
|
||||
resp, err := c.makeRequest("POST", "/comments", body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
Loading…
Reference in New Issue