Skip to content
Myr

Add HTTP example demonstrating I/O

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Christian Rocha · committed by Christian Rocha · parent a318d24 · Browse files · 1 file+85 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+85 added−0 removed

  • other:+85 added−0 removed

1 file+85 added−0 removed

added:examples/http/main.go+85 added
1package main23// A simple program that counts down from 5 and then exits.45import (6 "errors"7 "fmt"8 "log"9 "net/http"10 "time"1112 "github.com/charmbracelet/tea"13)1415const url = "https://charm.sh/"1617type Model struct {18 Status int19 Error error20}2122type statusMsg int2324func main() {25 p := tea.NewProgram(initialize, update, view, nil)26 if err := p.Start(); err != nil {27 log.Fatal(err)28 }29}3031func initialize() (tea.Model, tea.Cmd) {32 return Model{0, nil}, checkServer33}3435func update(msg tea.Msg, model tea.Model) (tea.Model, tea.Cmd) {36 m, _ := model.(Model)3738 switch msg := msg.(type) {3940 case tea.KeyMsg:41 switch msg.String() {42 case "esc":43 fallthrough44 case "break":45 fallthrough46 case "q":47 return m, tea.Quit48 default:49 return m, nil50 }5152 case statusMsg:53 m.Status = int(msg)54 return m, tea.Quit5556 case tea.ErrMsg:57 // TODO: get the error out of tea.ErrMsg less hackily58 m.Error = errors.New(msg.Error())59 return m, nil6061 default:62 return m, nil63 }64}6566func view(model tea.Model) string {67 m, _ := model.(Model)68 if m.Error != nil {69 return fmt.Sprintf("Something went wrong: %s", m.Error)70 } else if m.Status == 0 {71 return fmt.Sprintf("Checking %s...", url)72 }73 return fmt.Sprintf("The server said: %d %s", m.Status, http.StatusText(m.Status))74}7576func checkServer() tea.Msg {77 c := &http.Client{78 Timeout: 10 * time.Second,79 }80 res, err := c.Get(url)81 if err != nil {82 return tea.NewErrMsg(err.Error())83 }84 return statusMsg(res.StatusCode)85}