api.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. package api
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "path/filepath"
  8. "time"
  9. "k8s.io/client-go/util/homedir"
  10. )
  11. // Client represents the client for the Porter API
  12. type Client struct {
  13. BaseURL string
  14. HTTPClient *http.Client
  15. Cookie *http.Cookie
  16. CookieFilePath string
  17. }
  18. // HTTPError is the Porter error response returned if a request fails
  19. type HTTPError struct {
  20. Code uint `json:"code"`
  21. Errors []string `json:"errors"`
  22. }
  23. // NewClient constructs a new client based on a set of options
  24. func NewClient(baseURL string, cookieFileName string) *Client {
  25. home := homedir.HomeDir()
  26. cookieFilePath := filepath.Join(home, ".porter", cookieFileName)
  27. client := &Client{
  28. BaseURL: baseURL,
  29. CookieFilePath: cookieFilePath,
  30. HTTPClient: &http.Client{
  31. Timeout: time.Minute,
  32. },
  33. }
  34. cookie, _ := client.getCookie()
  35. if cookie != nil {
  36. client.Cookie = cookie
  37. }
  38. return client
  39. }
  40. func (c *Client) sendRequest(req *http.Request, v interface{}, useCookie bool) (*HTTPError, error) {
  41. req.Header.Set("Content-Type", "application/json; charset=utf-8")
  42. req.Header.Set("Accept", "application/json; charset=utf-8")
  43. if cookie, _ := c.getCookie(); useCookie && cookie != nil {
  44. c.Cookie = cookie
  45. req.AddCookie(c.Cookie)
  46. }
  47. res, err := c.HTTPClient.Do(req)
  48. if err != nil {
  49. return nil, err
  50. }
  51. defer res.Body.Close()
  52. if cookies := res.Cookies(); len(cookies) == 1 {
  53. c.saveCookie(cookies[0])
  54. }
  55. if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
  56. var errRes HTTPError
  57. if err = json.NewDecoder(res.Body).Decode(&errRes); err == nil {
  58. return &errRes, nil
  59. }
  60. return nil, fmt.Errorf("unknown error, status code: %d", res.StatusCode)
  61. }
  62. if v != nil {
  63. if err = json.NewDecoder(res.Body).Decode(v); err != nil {
  64. return nil, err
  65. }
  66. }
  67. return nil, nil
  68. }
  69. // CookieStorage for temporary fs-based cookie storage before jwt tokens
  70. type CookieStorage struct {
  71. Cookie *http.Cookie `json:"cookie"`
  72. }
  73. // saves single cookie to file
  74. func (c *Client) saveCookie(cookie *http.Cookie) error {
  75. data, err := json.Marshal(&CookieStorage{
  76. Cookie: cookie,
  77. })
  78. if err != nil {
  79. return err
  80. }
  81. return ioutil.WriteFile(c.CookieFilePath, data, 0644)
  82. }
  83. // retrieves single cookie from file
  84. func (c *Client) getCookie() (*http.Cookie, error) {
  85. data, err := ioutil.ReadFile(c.CookieFilePath)
  86. if err != nil {
  87. return nil, err
  88. }
  89. cookie := &CookieStorage{}
  90. err = json.Unmarshal(data, cookie)
  91. if err != nil {
  92. return nil, err
  93. }
  94. return cookie.Cookie, nil
  95. }