update examples. fix bugs
This commit is contained in:
+26
-31
@@ -2,6 +2,7 @@
|
||||
"HTTP request example - demonstrates async commands.
|
||||
Mirrors bubbletea's http example."
|
||||
(:require [tui.core :as tui]
|
||||
[tui.events :as ev]
|
||||
[clojure.java.io :as io])
|
||||
(:import [java.net URL HttpURLConnection]))
|
||||
|
||||
@@ -29,41 +30,35 @@
|
||||
:error nil
|
||||
:url "https://httpstat.us/200"})
|
||||
|
||||
;; === Commands ===
|
||||
(defn fetch-url [url]
|
||||
(fn []
|
||||
(let [result (http-get url)]
|
||||
(if (:error result)
|
||||
[:http-error (:error result)]
|
||||
[:http-success (:status result)]))))
|
||||
|
||||
;; === Update ===
|
||||
(defn update-model [{:keys [url] :as model} msg]
|
||||
(cond
|
||||
;; Quit
|
||||
(or (tui/key= msg "q")
|
||||
(tui/key= msg [:ctrl \c]))
|
||||
[model tui/quit]
|
||||
(defn update-fn [{:keys [model event]}]
|
||||
(let [{:keys [url]} model]
|
||||
(cond
|
||||
;; Quit
|
||||
(or (ev/key= event \q)
|
||||
(ev/key= event \c #{:ctrl}))
|
||||
{:model model :events [(ev/quit)]}
|
||||
|
||||
;; Enter - start request
|
||||
(and (= (:state model) :idle)
|
||||
(tui/key= msg :enter))
|
||||
[(assoc model :state :loading) (fetch-url url)]
|
||||
;; Enter - start request
|
||||
(and (= (:state model) :idle)
|
||||
(ev/key= event :enter))
|
||||
{:model (assoc model :state :loading)
|
||||
:events [(ev/shell ["curl" "-s" "-o" "/dev/null" "-w" "%{http_code}" url]
|
||||
{:type :http-result})]}
|
||||
|
||||
;; r - retry/reset
|
||||
(tui/key= msg "r")
|
||||
[(assoc model :state :idle :status nil :error nil) nil]
|
||||
;; r - retry/reset
|
||||
(ev/key= event \r)
|
||||
{:model (assoc model :state :idle :status nil :error nil)}
|
||||
|
||||
;; HTTP success
|
||||
(= (first msg) :http-success)
|
||||
[(assoc model :state :success :status (second msg)) nil]
|
||||
;; HTTP result
|
||||
(= (:type event) :http-result)
|
||||
(let [{:keys [success out err]} (:result event)]
|
||||
(if success
|
||||
{:model (assoc model :state :success :status (parse-long out))}
|
||||
{:model (assoc model :state :error :error err)}))
|
||||
|
||||
;; HTTP error
|
||||
(= (first msg) :http-error)
|
||||
[(assoc model :state :error :error (second msg)) nil]
|
||||
|
||||
:else
|
||||
[model nil]))
|
||||
:else
|
||||
{:model model})))
|
||||
|
||||
;; === View ===
|
||||
(defn view [{:keys [state status error url]} _size]
|
||||
@@ -105,7 +100,7 @@
|
||||
(defn -main [& _args]
|
||||
(println "Starting HTTP demo...")
|
||||
(let [final (tui/run {:init initial-model
|
||||
:update update-model
|
||||
:update update-fn
|
||||
:view view})]
|
||||
(when (= (:state final) :success)
|
||||
(println "Request completed with status:" (:status final)))))
|
||||
|
||||
Reference in New Issue
Block a user