1package handler
2
3import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "io"
8 "net/http"
9
10 "github.com/bnema/gordon/internal/cli"
11 "github.com/bnema/gordon/internal/common"
12)
13
14// PrepareJSONPayload marshals the payload into JSON
15func PrepareJSONPayload(payload common.Payload) ([]byte, error) {
16 return json.Marshal(payload)
17}
18
19// CreateNewRequest creates a new HTTP request
20func CreateNewRequest(method, url string, body []byte) (*http.Request, error) {
21
22 return http.NewRequest(method, url, bytes.NewBuffer(body))
23}
24
25// SetRequestHeaders sets the headers for the request
26func SetRequestHeaders(req *http.Request, token string) {
27 req.Header.Set("Content-Type", "application/json")
28 req.Header.Set("Authorization", "Bearer "+token)
29}
30
31// SendRequest sends the HTTP request and returns the response
32func SendRequest(req *http.Request) (*http.Response, error) {
33 client := &http.Client{}
34 return client.Do(req)
35}
36
37type Response struct {
38 Body []byte
39}
40
41// SendHTTPRequest sends the HTTP request
42func SendHTTPRequest(a *cli.App, rp *common.RequestPayload, method string, endpoint string) (*Response, error) {
43 apiUrl := a.Config.Http.BackendURL + "/api"
44 token := a.Config.General.Token
45
46 fmt.Printf("Final url:", apiUrl+endpoint)
47
48 // Prepare the entire RequestPayload, not just the inner Payload
49 jsonPayload, err := json.Marshal(rp)
50 if err != nil {
51 return nil, fmt.Errorf("failed to marshal payload: %w", err)
52 }
53 // Create a new request
54 req, err := CreateNewRequest(method, apiUrl+endpoint, jsonPayload)
55 if err != nil {
56 return nil, fmt.Errorf("failed to create new request: %w", err)
57 }
58 // Set the request headers
59 SetRequestHeaders(req, token)
60
61 // Send the request
62 resp, err := SendRequest(req)
63 if err != nil {
64 return nil, fmt.Errorf("failed to send request: %w", err)
65 }
66 defer resp.Body.Close()
67
68 // Read the response body
69 body, err := io.ReadAll(resp.Body)
70 if err != nil {
71 return nil, fmt.Errorf("failed to read response body: %w", err)
72 }
73 return &Response{Body: body}, nil
74}