2020-01-19 22:52:28 -05:00
|
|
|
package main
|
|
|
|
|
2020-10-14 07:35:50 -04:00
|
|
|
// A simple program that makes a GET request and prints the response status.
|
2020-01-19 22:52:28 -05:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
|
2020-05-25 19:26:40 -04:00
|
|
|
tea "github.com/charmbracelet/bubbletea"
|
2020-01-19 22:52:28 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
const url = "https://charm.sh/"
|
|
|
|
|
2020-10-15 19:48:42 -04:00
|
|
|
type model struct {
|
2020-04-22 11:00:30 -04:00
|
|
|
status int
|
|
|
|
err error
|
2020-01-19 22:52:28 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
type statusMsg int
|
2020-10-15 19:48:42 -04:00
|
|
|
|
|
|
|
type errMsg struct{ error }
|
|
|
|
|
|
|
|
func (e errMsg) Error() string { return e.Error() }
|
2020-01-19 22:52:28 -05:00
|
|
|
|
|
|
|
func main() {
|
2020-10-15 19:48:42 -04:00
|
|
|
p := tea.NewProgram(model{})
|
2020-01-19 22:52:28 -05:00
|
|
|
if err := p.Start(); err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-15 19:48:42 -04:00
|
|
|
func (m model) Init() tea.Cmd {
|
|
|
|
return checkServer
|
2020-01-19 22:52:28 -05:00
|
|
|
}
|
|
|
|
|
2020-10-15 19:48:42 -04:00
|
|
|
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
2020-01-19 22:52:28 -05:00
|
|
|
switch msg := msg.(type) {
|
|
|
|
|
2020-05-25 19:26:40 -04:00
|
|
|
case tea.KeyMsg:
|
2020-01-19 22:52:28 -05:00
|
|
|
switch msg.String() {
|
|
|
|
case "esc":
|
|
|
|
fallthrough
|
2020-01-26 16:46:30 -05:00
|
|
|
case "ctrl+c":
|
2020-01-19 22:52:28 -05:00
|
|
|
fallthrough
|
|
|
|
case "q":
|
2020-05-25 19:26:40 -04:00
|
|
|
return m, tea.Quit
|
2020-01-19 22:52:28 -05:00
|
|
|
default:
|
|
|
|
return m, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
case statusMsg:
|
2020-04-22 11:00:30 -04:00
|
|
|
m.status = int(msg)
|
2020-05-25 19:26:40 -04:00
|
|
|
return m, tea.Quit
|
2020-01-19 22:52:28 -05:00
|
|
|
|
2020-04-22 11:00:30 -04:00
|
|
|
case errMsg:
|
|
|
|
m.err = msg
|
2020-01-19 22:52:28 -05:00
|
|
|
return m, nil
|
|
|
|
|
|
|
|
default:
|
|
|
|
return m, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-15 19:48:42 -04:00
|
|
|
func (m model) View() string {
|
2020-04-22 10:15:04 -04:00
|
|
|
s := fmt.Sprintf("Checking %s...", url)
|
2020-04-22 11:00:30 -04:00
|
|
|
if m.err != nil {
|
|
|
|
s += fmt.Sprintf("something went wrong: %s", m.err)
|
|
|
|
} else if m.status != 0 {
|
|
|
|
s += fmt.Sprintf("%d %s", m.status, http.StatusText(m.status))
|
2020-01-19 22:52:28 -05:00
|
|
|
}
|
2020-05-12 17:05:16 -04:00
|
|
|
return s + "\n"
|
2020-01-19 22:52:28 -05:00
|
|
|
}
|
|
|
|
|
2020-05-25 19:26:40 -04:00
|
|
|
func checkServer() tea.Msg {
|
2020-01-19 22:52:28 -05:00
|
|
|
c := &http.Client{
|
|
|
|
Timeout: 10 * time.Second,
|
|
|
|
}
|
|
|
|
res, err := c.Get(url)
|
|
|
|
if err != nil {
|
2020-10-15 19:48:42 -04:00
|
|
|
return errMsg{err}
|
2020-01-19 22:52:28 -05:00
|
|
|
}
|
|
|
|
return statusMsg(res.StatusCode)
|
|
|
|
}
|