http_client.go 1013 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package functions
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "io/ioutil"
  6. "log"
  7. "net/http"
  8. )
  9. func Request[T any](method, route string, payload any) *T {
  10. requestURL := "http://localhost:3000"
  11. var (
  12. req *http.Request
  13. err error
  14. )
  15. if payload == nil {
  16. req, err = http.NewRequest(method, requestURL+route, nil)
  17. } else {
  18. payloadBytes, jsonErr := json.Marshal(payload)
  19. if jsonErr != nil {
  20. log.Fatalf("Error in request JSON marshalling: %s", err)
  21. }
  22. req, err = http.NewRequest(method, requestURL+route, bytes.NewReader(payloadBytes))
  23. }
  24. if err != nil {
  25. log.Fatalf("Client could not create request: %s", err)
  26. }
  27. res, err := http.DefaultClient.Do(req)
  28. if err != nil {
  29. log.Fatalf("Client error making http request: %s", err)
  30. }
  31. resBodyBytes, err := ioutil.ReadAll(res.Body)
  32. if err != nil {
  33. log.Fatalf("Client could not read response body: %s", err)
  34. }
  35. body := new(T)
  36. if err := json.Unmarshal(resBodyBytes, body); err != nil {
  37. log.Fatalf("Error unmarshalling JSON: %s", err)
  38. }
  39. return body
  40. }