Skip to content

Instantly share code, notes, and snippets.

@chico
Created February 24, 2022 09:02
Show Gist options
  • Save chico/446ecf4bee5660e2f9af39fc486c3bf3 to your computer and use it in GitHub Desktop.
Save chico/446ecf4bee5660e2f9af39fc486c3bf3 to your computer and use it in GitHub Desktop.
joke.go
package main
// A simple program that call a Joke API and prints out the joke
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
tea "github.com/charmbracelet/bubbletea"
)
const url = "https://sv443.net/jokeapi/v2/joke/Programming?type=single"
type model struct {
status string
err error
}
type jokejson struct {
Joke string `json:"joke"`
}
type statusMsg string
type errMsg struct{ error }
func (e errMsg) Error() string { return e.error.Error() }
func main() {
p := tea.NewProgram(model{})
if err := p.Start(); err != nil {
log.Fatal(err)
}
}
func (m model) Init() tea.Cmd {
return checkServer
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.String() {
case "q", "ctrl+c", "esc":
return m, tea.Quit
default:
return m, nil
}
case statusMsg:
m.status = string(msg)
return m, tea.Quit
case errMsg:
m.err = msg
return m, nil
default:
return m, nil
}
}
func (m model) View() string {
if m.err != nil {
return fmt.Sprintf("Something went wrong: %s", m.err)
} else if m.status != "" {
return fmt.Sprintf(m.status)
}
return ""
}
func checkServer() tea.Msg {
c := http.Client{
Timeout: time.Second * 30,
}
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
log.Fatal(err)
}
res, getErr := c.Do(req)
if getErr != nil {
log.Fatal(getErr)
}
if res.Body != nil {
defer res.Body.Close()
}
body, readErr := ioutil.ReadAll(res.Body)
if readErr != nil {
log.Fatal(readErr)
}
j := jokejson{}
jsonErr := json.Unmarshal(body, &j)
if jsonErr != nil {
log.Fatal(jsonErr)
}
return statusMsg(j.Joke)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment