bubbletea/examples/http/main.go

83 lines
1.3 KiB
Go
Raw Permalink Normal View History

2020-01-19 22:52:28 -05:00
package main
// A simple program that makes a GET request and prints the response status.
2020-01-19 22:52:28 -05:00
import (
"fmt"
"log"
"net/http"
"time"
tea "github.com/charmbracelet/bubbletea"
2020-01-19 22:52:28 -05:00
)
const url = "https://charm.sh/"
type model struct {
2020-04-22 11:00:30 -04:00
status int
err error
2020-01-19 22:52:28 -05:00
}
type statusMsg int
type errMsg struct{ error }
2021-04-09 01:57:58 -04:00
func (e errMsg) Error() string { return e.error.Error() }
2020-01-19 22:52:28 -05:00
func main() {
p := tea.NewProgram(model{})
if _, err := p.Run(); err != nil {
2020-01-19 22:52:28 -05:00
log.Fatal(err)
}
}
func (m model) Init() tea.Cmd {
return checkServer
2020-01-19 22:52:28 -05:00
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
2020-01-19 22:52:28 -05:00
switch msg := msg.(type) {
case tea.KeyMsg:
2020-01-19 22:52:28 -05:00
switch msg.String() {
2021-05-01 09:28:58 -04:00
case "q", "ctrl+c", "esc":
return m, tea.Quit
2020-01-19 22:52:28 -05:00
default:
return m, nil
}
case statusMsg:
2020-04-22 11:00:30 -04:00
m.status = int(msg)
return m, tea.Quit
2020-01-19 22:52:28 -05:00
2020-04-22 11:00:30 -04:00
case errMsg:
m.err = msg
2020-01-19 22:52:28 -05:00
return m, nil
default:
return m, nil
}
}
func (m model) View() string {
s := fmt.Sprintf("Checking %s...", url)
2020-04-22 11:00:30 -04:00
if m.err != nil {
s += fmt.Sprintf("something went wrong: %s", m.err)
} else if m.status != 0 {
s += fmt.Sprintf("%d %s", m.status, http.StatusText(m.status))
2020-01-19 22:52:28 -05:00
}
return s + "\n"
2020-01-19 22:52:28 -05:00
}
func checkServer() tea.Msg {
2020-01-19 22:52:28 -05:00
c := &http.Client{
Timeout: 10 * time.Second,
}
res, err := c.Get(url)
if err != nil {
return errMsg{err}
2020-01-19 22:52:28 -05:00
}
defer res.Body.Close()
2020-01-19 22:52:28 -05:00
return statusMsg(res.StatusCode)
}