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"
2020-05-12 16:39:08 -04:00
"github.com/charmbracelet/boba"
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() {
2020-05-12 16:39:08 -04:00
p := boba.NewProgram(initialize, update, view, nil)
2020-01-19 22:52:28 -05:00
if err := p.Start(); err != nil {
log.Fatal(err)
}
}
2020-05-12 16:39:08 -04:00
func initialize() (boba.Model, boba.Cmd) {
2020-01-19 22:52:28 -05:00
return Model{0, nil}, checkServer
}
2020-05-12 16:39:08 -04:00
func update(msg boba.Msg, model boba.Model) (boba.Model, boba.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) {
2020-05-12 16:39:08 -04:00
case boba.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":
2020-05-12 16:39:08 -04:00
return m, boba.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)
2020-05-12 16:39:08 -04:00
return m, boba.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
}
}
2020-05-12 16:39:08 -04:00
func view(model boba.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
2020-01-19 22:52:28 -05:00
}
2020-05-12 16:39:08 -04:00
func checkServer() boba.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)
}