main.go
This file
Path
tutorials/commands/main.go
78 lines · 1.4 KiB · Go
Last changed by
Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
History of this fileTake it
1package main23import (4 "fmt"5 "net/http"6 "os"7 "time"89 tea "charm.land/bubbletea/v2"10)1112const url = "https://charm.sh/"1314type model struct {15 status int16 err error17}1819func checkServer() tea.Msg {20 c := &http.Client{Timeout: 10 * time.Second}21 res, err := c.Get(url)22 if err != nil {23 return errMsg{err}24 }25 defer res.Body.Close() // nolint:errcheck2627 return statusMsg(res.StatusCode)28}2930type statusMsg int3132type errMsg struct{ err error }3334// For messages that contain errors it's often handy to also implement the35// error interface on the message.36func (e errMsg) Error() string { return e.err.Error() }3738func (m model) Init() tea.Cmd {39 return checkServer40}4142func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {43 switch msg := msg.(type) {44 case statusMsg:45 m.status = int(msg)46 return m, tea.Quit4748 case errMsg:49 m.err = msg50 return m, tea.Quit5152 case tea.KeyPressMsg:53 if msg.Mod == tea.ModCtrl && msg.Code == 'c' {54 return m, tea.Quit55 }56 }5758 return m, nil59}6061func (m model) View() tea.View {62 if m.err != nil {63 return tea.NewView(fmt.Sprintf("\nWe had some trouble: %v\n\n", m.err))64 }6566 s := fmt.Sprintf("Checking %s ... ", url)67 if m.status > 0 {68 s += fmt.Sprintf("%d %s!", m.status, http.StatusText(m.status))69 }70 return tea.NewView("\n" + s + "\n\n")71}7273func main() {74 if _, err := tea.NewProgram(model{}).Run(); err != nil {75 fmt.Printf("Uh oh, there was an error: %v\n", err)76 os.Exit(1)77 }78}