commit e4b9073ff7e1c23f1921f1b1f03e54ef9209c5c9 Author: GeneralHurricane Date: Sat Dec 17 07:03:35 2022 -0600 fsdfsd diff --git a/rdrama.go b/rdrama.go new file mode 100644 index 0000000..6801b54 --- /dev/null +++ b/rdrama.go @@ -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 +}