Skip to content

Commit

Permalink
cleanup: move creation of http.Request to function (#31)
Browse files Browse the repository at this point in the history
  • Loading branch information
xx4h authored Oct 12, 2024
1 parent 88b8d58 commit 13ed3c0
Showing 1 changed file with 20 additions and 17 deletions.
37 changes: 20 additions & 17 deletions pkg/rest/rest.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,32 +61,35 @@ func (h *Hass) preflight() error {
return nil
}

func (h *Hass) api(meth string, path string, payload map[string]any) ([]byte, error) {
if err := h.preflight(); err != nil {
return nil, err
}
client := &http.Client{}
var req *http.Request
var err error
func (h *Hass) createRequest(meth string, path string, payload map[string]any) (*http.Request, error) {
var r io.Reader

if payload != nil {
jayload, err := json.Marshal(payload)
if err != nil {
return nil, err
}
req, err = http.NewRequest(meth, fmt.Sprintf("%s%s", h.APIURL, path), bytes.NewBuffer(jayload))
if err != nil {
return nil, err
}
} else {
req, err = http.NewRequest(meth, fmt.Sprintf("%s%s", h.APIURL, path), nil)
b, err := json.Marshal(payload)
if err != nil {
return nil, err
}
r = bytes.NewBuffer(b)
}

return http.NewRequest(meth, fmt.Sprintf("%s%s", h.APIURL, path), r)
}

func (h *Hass) api(meth string, path string, payload map[string]any) ([]byte, error) {
if err := h.preflight(); err != nil {
return nil, err
}

req, err := h.createRequest(meth, path, payload)
if err != nil {
return nil, err
}

log.Info().Msgf("Requesting URL %s, Method %s, Payload: %#v", req.URL, req.Method, payload)
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", h.Token))
req.Header.Set("Content-Type", "application/json")

client := &http.Client{}
res, err := client.Do(req)
if err != nil {
return nil, err
Expand Down

0 comments on commit 13ed3c0

Please sign in to comment.