Change to HTTP Model (#5)

This commit is contained in:
Harrison (Harry) Cramer
2023-05-19 17:28:58 -07:00
committed by GitHub
parent fe0d09d582
commit 63fc025070
21 changed files with 689 additions and 430 deletions

View File

@@ -1,6 +1,7 @@
package main
import (
"encoding/json"
"errors"
"fmt"
"io"
@@ -10,13 +11,13 @@ import (
const mrUrl = "https://gitlab.com/api/v4/projects/%s/merge_requests/%d"
func (c *Client) Info() error {
func (c *Client) Info() ([]byte, error) {
url := fmt.Sprintf(mrUrl, c.projectId, c.mergeId)
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return fmt.Errorf("Failed to build read request: %w", err)
return nil, fmt.Errorf("Failed to build read request: %w", err)
}
req.Header.Set("PRIVATE-TOKEN", os.Getenv("GITLAB_TOKEN"))
@@ -25,22 +26,42 @@ func (c *Client) Info() error {
res, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("Failed to make info request: %w", err)
return nil, fmt.Errorf("Failed to make info request: %w", err)
}
defer res.Body.Close()
if res.StatusCode < 200 || res.StatusCode >= 300 {
return errors.New(fmt.Sprintf("Recieved non-200 response: %d", res.StatusCode))
return nil, errors.New(fmt.Sprintf("Recieved non-200 response: %d", res.StatusCode))
}
body, err := io.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("Failed to parse read response: %w", err)
return nil, fmt.Errorf("Failed to parse read response: %w", err)
}
/* This response is parsed into a table in our Lua code */
fmt.Println(string(body))
return body, nil
return nil
}
func InfoHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/json")
client := r.Context().Value("client").(Client)
msg, err := client.Info()
if err != nil {
errResp := map[string]string{"message": err.Error()}
response, _ := json.Marshal(errResp)
w.WriteHeader(http.StatusInternalServerError)
w.Write(response)
return
}
w.WriteHeader(http.StatusOK)
w.Write(msg)
}