Skip to content
Myr

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 file

Take 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 back
1# Commands in Bubble Tea

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 2–8why, one step back
2
3This 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].8

docs: fix links to tutorials & examples (#1645)mhdnabefore adoption882727b

line 9why, one step back
9[basics]: https://github.com/charmbracelet/bubbletea/tree/main/tutorials/basics

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 10–11why, one step back
10[source]: https://github.com/charmbracelet/bubbletea/blob/master/tutorials/commands/main.go
11

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 12why, one step back
12## Let’s Go!

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

line 13why, one step back
13

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 14why, one step back
14For this tutorial we’re building a very simple program that makes an HTTP

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 15–16why, one step back
15request to a server and reports the status code of the response.
16

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 17why, one step back
17We’ll import a few necessary packages and put the URL we’re going to check in

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 18–28why, one step back
18a `const`.
1920```go21package main2223import (24 "fmt"25 "net/http"26 "os"27 "time"28

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 29why, one step back
29 tea "charm.land/bubbletea/v2"

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 30–36why, one step back
30)
3132const url = "https://charm.sh/"33```3435## The Model36

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 37why, one step back
37Next we’ll define our model. The only things we need to store are the status

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 38–53why, one step back
38code 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.53

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 54why, one step back
54Anyway, let’s write a `Cmd` that makes a request to a server and returns the

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 55–82why, one step back
55result 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```82

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

lines 83–85why, one step back
83And notice that we’ve defined two new `Msg` types. They can be any type, even
84an 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 back
86
87## 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 back
90Note that we don’t call the function; the Bubble Tea runtime will do that when

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 91–93why, one step back
91the time is right.
9293```go

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 94why, one step back
94func (m model) Init() tea.Cmd {

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 95–123why, one step back
95 return checkServer
96}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.Quit123

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 124why, one step back
124 case tea.KeyPressMsg:

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 125–127why, one step back
125 // Ctrl+c exits. Even with short running programs it's good to have
126 // 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 back
128 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 back
131 }
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 a

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 141why, one step back
141`tea.View` accordingly:

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 142–143why, one step back
142
143```go

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 144why, one step back
144func (m model) View() tea.View {

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 145–146why, one step back
145 // 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 back
147 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 back
148 }
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 back
159 return tea.NewView("\n" + s + "\n\n")

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 160–164why, one step back
160}
161```162163## Run the program164

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

lines 165–166why, one step back
165The only thing left to do is run the program, so let’s do that! Our initial
166model doesn’t need any data at all in this case, we just initialize it with

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 167–177why, one step back
167a `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```177

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 178why, one step back
178And that’s that. There’s one more thing that is helpful to know about

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 179–182why, one step back
179`Cmd`s, though.
180181## One More Thing About Commands182

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

lines 183–184why, one step back
183`Cmd`s are defined in Bubble Tea as `type Cmd func() Msg`. So they’re just
184functions that don’t take any arguments and return a `Msg`, which can be

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 185–211why, one step back
185any type. If you need to pass arguments to a command, you just make a function
186that 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 innermost

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 212why, one step back
212function, because that’s the one that runs asynchronously.

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 213–223why, one step back
213
214## 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/bubbles

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 224why, one step back
224[docs]: https://pkg.go.dev/charm.land/bubbletea/v2?tab=doc

docs: fix links to tutorials & examples (#1645)mhdnabefore adoption882727b

line 225why, one step back
225[examples]: https://github.com/charmbracelet/bubbletea/tree/main/examples

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 226–228why, one step back
226
227## Additional Resources228

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

lines 229–230why, one step back
229- [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 back
231
232### Feedback233

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 234why, one step back
234We’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 back
235

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

lines 236–238why, one step back
236- [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 back
239

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 240why, one step back
240---

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 241–246why, one step back
241
242Part 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