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

@@ -2,40 +2,90 @@ package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"io"
"net/http"
"time"
"github.com/xanzy/go-gitlab"
)
func (c *Client) Reply() error {
type ReplyRequest struct {
DiscussionId string `json:"discussion_id"`
Reply string `json:"reply"`
}
if len(os.Args) < 5 {
return errors.New("Must provide discussionId and reply text")
}
type ReplyResponse struct {
SuccessResponse
Note *gitlab.Note `json:"note"`
}
discussionId, reply := os.Args[3], os.Args[4]
func (c *Client) Reply(r ReplyRequest) (*gitlab.Note, int, error) {
now := time.Now()
options := gitlab.AddMergeRequestDiscussionNoteOptions{
Body: gitlab.String(reply),
Body: gitlab.String(r.Reply),
CreatedAt: &now,
}
gitlabNote, _, err := c.git.Discussions.AddMergeRequestDiscussionNote(c.projectId, c.mergeId, discussionId, &options)
note, res, err := c.git.Discussions.AddMergeRequestDiscussionNote(c.projectId, c.mergeId, r.DiscussionId, &options)
if err != nil {
return fmt.Errorf("Could not leave reply: %w", err)
return nil, res.Response.StatusCode, fmt.Errorf("Could not leave reply: %w", err)
}
output, err := json.Marshal(gitlabNote)
if err != nil {
return fmt.Errorf("Could not marshal note: %w", err)
}
fmt.Println(string(output))
return nil
return note, http.StatusOK, nil
}
func ReplyHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/json")
c := r.Context().Value("client").(Client)
body, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
errMsg := map[string]string{"message": "Could not read request body"}
jsonMsg, _ := json.Marshal(errMsg)
w.Write(jsonMsg)
return
}
defer r.Body.Close()
var replyRequest ReplyRequest
err = json.Unmarshal(body, &replyRequest)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
errMsg := map[string]string{"message": "Could not read JSON from request"}
jsonMsg, _ := json.Marshal(errMsg)
w.Write(jsonMsg)
return
}
note, status, err := c.Reply(replyRequest)
w.Header().Set("Content-Type", "application/json")
if err != nil {
response := ErrorResponse{
Message: err.Error(),
Status: status,
}
json.NewEncoder(w).Encode(response)
return
}
response := ReplyResponse{
SuccessResponse: SuccessResponse{
Message: fmt.Sprintf("Replied: %s", note.Body),
Status: http.StatusOK,
},
Note: note,
}
json.NewEncoder(w).Encode(response)
}