| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- package httpbackend
- import (
- "encoding/json"
- "fmt"
- "io/ioutil"
- "net/http"
- "time"
- )
- type Client struct {
- backendURL string
- httpClient *http.Client
- }
- func NewClient(backendURL string) *Client {
- httpClient := &http.Client{
- Timeout: time.Minute,
- }
- return &Client{backendURL, httpClient}
- }
- func (c *Client) GetCurrentState(name string) (*TFState, error) {
- resp := &TFState{}
- err := c.getRequest(fmt.Sprintf("%s/%s/tfstate", c.backendURL, name), resp)
- return resp, err
- }
- func (c *Client) GetDesiredState(name string) (*DesiredTFState, error) {
- resp := &DesiredTFState{}
- err := c.getRequest(fmt.Sprintf("%s/%s/state", c.backendURL, name), resp)
- return resp, err
- }
- func (c *Client) getRequest(path string, dst interface{}) error {
- req, err := http.NewRequest(
- "GET",
- path,
- nil,
- )
- if err != nil {
- return err
- }
- req.Header.Set("Content-Type", "application/json; charset=utf-8")
- req.Header.Set("Accept", "application/json; charset=utf-8")
- res, err := c.httpClient.Do(req)
- if err != nil {
- return err
- }
- defer res.Body.Close()
- if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
- resBytes, err := ioutil.ReadAll(res.Body)
- if err != nil {
- return fmt.Errorf("request failed with status code %d, but could not read body (%s)\n", res.StatusCode, err.Error())
- }
- return fmt.Errorf("request failed with status code %d: %s\n", res.StatusCode, string(resBytes))
- }
- if dst != nil {
- return json.NewDecoder(res.Body).Decode(dst)
- }
- return nil
- }
|