api.go 2.8 KB

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