README.md
This file
Path
tutorials/commands/README.md
246 lines · 7.1 KiB · Markdown
Last changed by
docs: fix links to tutorials & examples (#1645)mhdnabefore adoption882727b
History of this fileTake it
The walk stopped after 200 commits: lines older than 3dfbcd9 point at it.
Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 1why, one step back1# Commands in Bubble Teafeat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 2–8why, one step back23This is the second tutorial for Bubble Tea covering commands, which deal with4I/O. The tutorial assumes you have a working knowledge of Go and a decent5understanding of [the first tutorial][basics].67You can find the non-annotated version of this program [on GitHub][source].8docs: fix links to tutorials & examples (#1645)mhdnabefore adoption882727b
line 9why, one step back9[basics]: https://github.com/charmbracelet/bubbletea/tree/main/tutorials/basicsfeat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 10–11why, one step back10[source]: https://github.com/charmbracelet/bubbletea/blob/master/tutorials/commands/main.go11Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 12why, one step back12## Let’s Go!feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 13why, one step back13Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 14why, one step back14For this tutorial we’re building a very simple program that makes an HTTPfeat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 15–16why, one step back15request to a server and reports the status code of the response.16Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 17why, one step back17We’ll import a few necessary packages and put the URL we’re going to check infeat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 18–28why, one step back18a `const`.1920```go21package main2223import (24 "fmt"25 "net/http"26 "os"27 "time"28Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 29why, one step back29 tea "charm.land/bubbletea/v2"feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 30–36why, one step back30)3132const url = "https://charm.sh/"33```3435## The Model36Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 37why, one step back37Next we’ll define our model. The only things we need to store are the statusfeat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 38–53why, one step back38code of the HTTP response and a possible error.3940```go41type model struct {42 status int43 err error44}45```4647## Commands and Messages4849`Cmd`s are functions that perform some I/O and then return a `Msg`. Checking the50time, ticking a timer, reading from the disk, and network stuff are all I/O and51should be run through commands. That might sound harsh, but it will keep your52Bubble Tea program straightforward and simple.53Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 54why, one step back54Anyway, let’s write a `Cmd` that makes a request to a server and returns thefeat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 55–82why, one step back55result as a `Msg`.5657```go58func checkServer() tea.Msg {5960 // Create an HTTP client and make a GET request.61 c := &http.Client{Timeout: 10 * time.Second}62 res, err := c.Get(url)6364 if err != nil {65 // There was an error making our request. Wrap the error we received66 // in a message and return it.67 return errMsg{err}68 }69 // We received a response from the server. Return the HTTP status code70 // as a message.71 return statusMsg(res.StatusCode)72}7374type statusMsg int7576type errMsg struct{ err error }7778// For messages that contain errors it's often handy to also implement the79// error interface on the message.80func (e errMsg) Error() string { return e.err.Error() }81```82Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 83–85why, one step back83And notice that we’ve defined two new `Msg` types. They can be any type, even84an empty struct. We’ll come back to them later in our update function.85First, let’s write our initialization function.feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 86–89why, one step back8687## The Initialization Method8889The initialization method is very simple: we return the `Cmd` we made earlier.Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 90why, one step back90Note that we don’t call the function; the Bubble Tea runtime will do that whenfeat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 91–93why, one step back91the time is right.9293```goMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 94why, one step back94func (m model) Init() tea.Cmd {feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 95–123why, one step back95 return checkServer96}97```9899## The Update Method100101Internally, `Cmd`s run asynchronously in a goroutine. The `Msg` they return is102collected and sent to our update function for handling. Remember those message103types we made earlier when we were making the `checkServer` command? We handle104them here. This makes dealing with many asynchronous operations very easy.105106```go107func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {108 switch msg := msg.(type) {109110 case statusMsg:111 // The server returned a status message. Save it to our model. Also112 // tell the Bubble Tea runtime we want to exit because we have nothing113 // else to do. We'll still be able to render a final view with our114 // status message.115 m.status = int(msg)116 return m, tea.Quit117118 case errMsg:119 // There was an error. Note it in the model. And tell the runtime120 // we're done and want to quit.121 m.err = msg122 return m, tea.Quit123Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 124why, one step back124 case tea.KeyPressMsg:feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 125–127why, one step back125 // Ctrl+c exits. Even with short running programs it's good to have126 // a quit key, just in case your logic is off. Users will be very127 // annoyed if they can't exit.Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 128–130why, one step back128 if msg.Mod == tea.ModCtrl && msg.Code == 'c' {129 return m, tea.Quit130 }feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 131–140why, one step back131 }132133 // If we happen to get any other messages, don't do anything.134 return m, nil135}136```137138## The View Function139140Our view is very straightforward. We look at the current model and build aMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 141why, one step back141`tea.View` accordingly:feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 142–143why, one step back142143```goMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 144why, one step back144func (m model) View() tea.View {feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 145–146why, one step back145 // If there's an error, print it out and don't do anything else.146 if m.err != nil {Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 147why, one step back147 return tea.NewView(fmt.Sprintf("\nWe had some trouble: %v\n\n", m.err))feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 148–158why, one step back148 }149150 // Tell the user we're doing something.151 s := fmt.Sprintf("Checking %s ... ", url)152153 // When the server responds with a status, add it to the current line.154 if m.status > 0 {155 s += fmt.Sprintf("%d %s!", m.status, http.StatusText(m.status))156 }157158 // Send off whatever we came up with above for rendering.Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 159why, one step back159 return tea.NewView("\n" + s + "\n\n")feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 160–164why, one step back160}161```162163## Run the program164Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 165–166why, one step back165The only thing left to do is run the program, so let’s do that! Our initial166model doesn’t need any data at all in this case, we just initialize it withfeat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 167–177why, one step back167a `model` struct with default values.168169```go170func main() {171 if _, err := tea.NewProgram(model{}).Run(); err != nil {172 fmt.Printf("Uh oh, there was an error: %v\n", err)173 os.Exit(1)174 }175}176```177Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 178why, one step back178And that’s that. There’s one more thing that is helpful to know aboutfeat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 179–182why, one step back179`Cmd`s, though.180181## One More Thing About Commands182Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 183–184why, one step back183`Cmd`s are defined in Bubble Tea as `type Cmd func() Msg`. So they’re just184functions that don’t take any arguments and return a `Msg`, which can befeat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 185–211why, one step back185any type. If you need to pass arguments to a command, you just make a function186that returns a command. For example:187188```go189func cmdWithArg(id int) tea.Cmd {190 return func() tea.Msg {191 return someMsg{id: id}192 }193}194```195196A more real-world example looks like:197198```go199func checkSomeUrl(url string) tea.Cmd {200 return func() tea.Msg {201 c := &http.Client{Timeout: 10 * time.Second}202 res, err := c.Get(url)203 if err != nil {204 return errMsg{err}205 }206 return statusMsg(res.StatusCode)207 }208}209```210211Anyway, just make sure you do as much stuff as you can in the innermostMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 212why, one step back212function, because that’s the one that runs asynchronously.feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 213–223why, one step back213214## Now What?215216After doing this tutorial and [the previous one][basics] you should be ready to217build a Bubble Tea program of your own. We also recommend that you look at the218Bubble Tea [example programs][examples] as well as [Bubbles][bubbles],219a component library for Bubble Tea.220221And, of course, check out the [Go Docs][docs].222223[bubbles]: https://github.com/charmbracelet/bubblesMerge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 224why, one step back224[docs]: https://pkg.go.dev/charm.land/bubbletea/v2?tab=docdocs: fix links to tutorials & examples (#1645)mhdnabefore adoption882727b
line 225why, one step back225[examples]: https://github.com/charmbracelet/bubbletea/tree/main/examplesfeat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 226–228why, one step back226227## Additional Resources228Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 229–230why, one step back229- [Libraries we use with Bubble Tea](https://github.com/charmbracelet/bubbletea/#libraries-we-use-with-bubble-tea)230- [Bubble Tea in the Wild](https://github.com/charmbracelet/bubbletea/#bubble-tea-in-the-wild)feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 231–233why, one step back231232### Feedback233Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 234why, one step back234We’d love to hear your thoughts on this tutorial. Feel free to drop us a note!feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 235why, one step back235Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
lines 236–238why, one step back236- [Twitter](https://twitter.com/charmcli)237- [The Fediverse](https://mastodon.social/@charmcli)238- [Discord](https://charm.sh/chat)feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
line 239why, one step back239Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
line 240why, one step back240---feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9
lines 241–246why, one step back241242Part of [Charm](https://charm.sh).243244<a href="https://charm.sh/"><img alt="The Charm logo" src="https://stuff.charm.sh/charm-badge.jpg" width="400"></a>245246Charm热爱开源 • Charm loves open source