Created
July 17, 2013 21:08
-
-
Save christianromney/6024513 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns circuito.core | |
(:require [clojure.core.async :as async :refer :all]) | |
(:gen-class)) | |
(def ^:dynamic *timeout* 300) | |
;; Like defn, but executes body in a go block, allowing at most *timeout* milliseconds for completion | |
(defmacro defcommand [name args & body] | |
`(defn ~name ~args | |
(let [t# (timeout *timeout*) | |
c# (chan)] | |
(go (>! c# (do ~@body))) | |
(<!! (go | |
(let [[r# ch#] (alts! [t# c#])] | |
(if (= ch# t#) :timeout r#))))))) | |
(defcommand fetch-url | |
[url] | |
(slurp url)) | |
(defn- to-int | |
"Tries to coerce a value to an integer" | |
[val] | |
(when val | |
(cond (integer? val) val | |
(number? val) (int val) | |
(string? val) (int (Integer/parseInt val))))) | |
(defn -main | |
"Fetch the URL in the first arg in second arg (or default) milliseconds" | |
[& args] | |
(let [uri (first args) | |
t (or (to-int (second args)) *timeout*)] | |
(binding [*timeout* t] | |
(println | |
(fetch-url uri))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment