master
GeneralHurricane 2022-12-17 07:03:35 -06:00
commit e4b9073ff7
1 changed files with 76 additions and 0 deletions

76
rdrama.go 100644
View File

@ -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
}