diff --git a/internal/setup/flag_toggle.go b/internal/setup/flag_toggle.go index 789d92ca..3d9ba8ad 100644 --- a/internal/setup/flag_toggle.go +++ b/internal/setup/flag_toggle.go @@ -1,7 +1,11 @@ package setup import ( + "bytes" "fmt" + "net/http" + "time" + "github.com/charmbracelet/bubbles/key" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" @@ -11,6 +15,7 @@ type flagToggleModel struct { enabled bool flagKey string logType string + //err error } func NewFlagToggle() flagToggleModel { @@ -27,6 +32,9 @@ func (m flagToggleModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch { case key.Matches(msg, keys.Toggle): m.enabled = !m.enabled + + // uncomment to send PATCH + //m.err = m.toggleFlag() } } @@ -53,3 +61,32 @@ func (m flagToggleModel) View() string { return title + "\n\n" + toggleStyle.Render(toggle) + m.flagKey + furtherInstructions } + +func (m flagToggleModel) toggleFlag() error { + url := fmt.Sprintf("http://localhost/api/v2/flags/default/%s", m.flagKey) + c := &http.Client{ + Timeout: 10 * time.Second, + } + + toggleInstruction := "turnFlagOn" + if !m.enabled { + toggleInstruction = "turnFlagOff" + } + + body := fmt.Sprintf(`{ + "environmentKey": "test", + "instructions": [ { "kind": %q } ] + }`, toggleInstruction) + + req, _ := http.NewRequest("PATCH", url, bytes.NewBufferString(body)) + req.Header.Add("Authorization", apiToken) // add token here + req.Header.Add("Content-type", "application/json; domain-model=launchdarkly.semanticpatch") + + res, err := c.Do(req) + if err != nil { + return err + } + defer res.Body.Close() + + return nil +} diff --git a/internal/setup/flags.go b/internal/setup/flags.go index 07c813d0..193f8a1f 100644 --- a/internal/setup/flags.go +++ b/internal/setup/flags.go @@ -1,7 +1,10 @@ package setup import ( + "bytes" "fmt" + "net/http" + "time" "github.com/charmbracelet/bubbles/key" "github.com/charmbracelet/bubbles/list" @@ -26,6 +29,7 @@ func (p flag) FilterValue() string { return "" } type flagModel struct { input string textInput textinput.Model + //err error } func NewFlag() tea.Model { @@ -55,6 +59,9 @@ func (m flagModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { input = defaultFlagKey } m.input = input + + // uncomment to send POST + //m.err = m.createFlag() case key.Matches(msg, keys.Quit): return m, tea.Quit default: @@ -74,3 +81,32 @@ func (m flagModel) View() string { style.Render(m.textInput.View()), ) + "\n" } + +const apiToken = "" + +func (m flagModel) createFlag() error { + url := "http://localhost/api/v2/flags/default" + c := &http.Client{ + Timeout: 10 * time.Second, + } + + body := fmt.Sprintf(`{ + "name": %q, + "key": %q + }`, + m.input, + m.input, + ) + + req, _ := http.NewRequest("POST", url, bytes.NewBufferString(body)) + req.Header.Add("Authorization", apiToken) // add token here + req.Header.Add("Content-type", "application/json") + + res, err := c.Do(req) + if err != nil { + return err + } + defer res.Body.Close() + + return nil +}