2
0

backend.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package httpbackend
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "time"
  8. )
  9. type Client struct {
  10. backendURL string
  11. httpClient *http.Client
  12. }
  13. func NewClient(backendURL string) *Client {
  14. httpClient := &http.Client{
  15. Timeout: time.Minute,
  16. }
  17. return &Client{backendURL, httpClient}
  18. }
  19. func (c *Client) GetCurrentState(name string) (*TFState, error) {
  20. resp := &TFState{}
  21. err := c.getRequest(fmt.Sprintf("%s/%s/tfstate", c.backendURL, name), resp)
  22. return resp, err
  23. }
  24. type GetDesiredStateResp struct {
  25. Data *DesiredTFState `json:"data"`
  26. }
  27. func (c *Client) GetDesiredState(name string) (*DesiredTFState, error) {
  28. resp := &GetDesiredStateResp{}
  29. err := c.getRequest(fmt.Sprintf("%s/%s/state", c.backendURL, name), resp)
  30. if err != nil {
  31. return nil, err
  32. }
  33. return resp.Data, nil
  34. }
  35. var ErrNotFound = fmt.Errorf("Not found")
  36. func (c *Client) getRequest(path string, dst interface{}) error {
  37. req, err := http.NewRequest(
  38. "GET",
  39. path,
  40. nil,
  41. )
  42. if err != nil {
  43. return err
  44. }
  45. req.Header.Set("Content-Type", "application/json; charset=utf-8")
  46. req.Header.Set("Accept", "application/json; charset=utf-8")
  47. res, err := c.httpClient.Do(req)
  48. if err != nil {
  49. return err
  50. }
  51. defer res.Body.Close()
  52. if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
  53. resBytes, err := ioutil.ReadAll(res.Body)
  54. if err != nil {
  55. return fmt.Errorf("request failed with status code %d, but could not read body (%s)\n", res.StatusCode, err.Error())
  56. }
  57. if res.StatusCode == http.StatusNotFound {
  58. return ErrNotFound
  59. }
  60. return fmt.Errorf("request failed with status code %d: %s\n", res.StatusCode, string(resBytes))
  61. }
  62. if dst != nil {
  63. return json.NewDecoder(res.Body).Decode(dst)
  64. }
  65. return nil
  66. }