bubbletea/examples/http/main.go

90 lines
1.5 KiB
Go
Raw Normal View History

2020-01-19 22:52:28 -05:00
package main
// A simple program that counts down from 5 and then exits.
import (
"errors"
"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
2020-04-22 11:00:30 -04:00
type errMsg error
2020-01-19 22:52:28 -05:00
func main() {
p := tea.NewProgram(initialize, update, view)
2020-01-19 22:52:28 -05:00
if err := p.Start(); err != nil {
log.Fatal(err)
}
}
func initialize() (tea.Model, tea.Cmd) {
2020-01-19 22:52:28 -05:00
return Model{0, nil}, checkServer
}
func update(msg tea.Msg, model tea.Model) (tea.Model, tea.Cmd) {
2020-04-22 11:00:30 -04:00
m, ok := model.(Model)
if !ok {
return Model{err: errors.New("could not perform assertion on model during update")}, nil
}
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() {
case "esc":
fallthrough
case "ctrl+c":
2020-01-19 22:52:28 -05:00
fallthrough
case "q":
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 view(model tea.Model) string {
2020-01-19 22:52:28 -05:00
m, _ := model.(Model)
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 {
2020-04-22 11:00:30 -04:00
return errMsg(err)
2020-01-19 22:52:28 -05:00
}
return statusMsg(res.StatusCode)
}