http_client.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package functions
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "io"
  6. "log"
  7. "net/http"
  8. "github.com/gravitl/netmaker/cli/config"
  9. "github.com/gravitl/netmaker/models"
  10. )
  11. func getAuthToken(ctx config.Context) string {
  12. authParams := &models.UserAuthParams{UserName: ctx.Username, Password: ctx.Password}
  13. payload, err := json.Marshal(authParams)
  14. if err != nil {
  15. log.Fatal(err)
  16. }
  17. res, err := http.Post(ctx.Endpoint+"/api/users/adm/authenticate", "application/json", bytes.NewReader(payload))
  18. if err != nil {
  19. log.Fatal(err)
  20. }
  21. resBodyBytes, err := io.ReadAll(res.Body)
  22. if err != nil {
  23. log.Fatalf("Client could not read response body: %s", err)
  24. }
  25. if res.StatusCode != http.StatusOK {
  26. log.Fatalf("Error response: %s", string(resBodyBytes))
  27. }
  28. body := new(models.SuccessResponse)
  29. if err := json.Unmarshal(resBodyBytes, body); err != nil {
  30. log.Fatalf("Error unmarshalling JSON: %s", err)
  31. }
  32. return body.Response.(map[string]any)["AuthToken"].(string)
  33. }
  34. func request[T any](method, route string, payload any) *T {
  35. var (
  36. ctx = config.GetCurrentContext()
  37. req *http.Request
  38. err error
  39. )
  40. if payload == nil {
  41. req, err = http.NewRequest(method, ctx.Endpoint+route, nil)
  42. if err != nil {
  43. log.Fatalf("Client could not create request: %s", err)
  44. }
  45. } else {
  46. payloadBytes, jsonErr := json.Marshal(payload)
  47. if jsonErr != nil {
  48. log.Fatalf("Error in request JSON marshalling: %s", err)
  49. }
  50. req, err = http.NewRequest(method, ctx.Endpoint+route, bytes.NewReader(payloadBytes))
  51. if err != nil {
  52. log.Fatalf("Client could not create request: %s", err)
  53. }
  54. req.Header.Set("Content-Type", "application/json")
  55. }
  56. if ctx.MasterKey != "" {
  57. req.Header.Set("Authorization", "Bearer "+ctx.MasterKey)
  58. } else {
  59. req.Header.Set("Authorization", "Bearer "+getAuthToken(ctx))
  60. }
  61. res, err := http.DefaultClient.Do(req)
  62. if err != nil {
  63. log.Fatalf("Client error making http request: %s", err)
  64. }
  65. resBodyBytes, err := io.ReadAll(res.Body)
  66. if err != nil {
  67. log.Fatalf("Client could not read response body: %s", err)
  68. }
  69. if res.StatusCode != http.StatusOK {
  70. log.Fatalf("Error response: %s", string(resBodyBytes))
  71. }
  72. body := new(T)
  73. if err := json.Unmarshal(resBodyBytes, body); err != nil {
  74. log.Fatalf("Error unmarshalling JSON: %s", err)
  75. }
  76. return body
  77. }