1
0
mirror of https://github.com/janet-lang/janet synced 2025-09-10 23:06:08 +00:00

Add urlloader example.

Demonstrate loading files from URL.
This commit is contained in:
Calvin Rose
2019-05-25 17:10:25 -04:00
parent 0280deccae
commit 840610facf
3 changed files with 46 additions and 9 deletions

28
examples/urlloader.janet Normal file
View File

@@ -0,0 +1,28 @@
# An example of using Janet's extensible module system
# to import files from URL. To try this, run `janet -l examples/urlloader.janet`
# from the repl, and then:
#
# (import https://raw.githubusercontent.com/janet-lang/janet/master/examples/colors.janet :as c)
#
# This will import a file using curl. You can then try
#
# (print (c/color :green "Hello!"))
#
# This is a bit of a toy example (it just shells out to curl), but it is very
# powerful and will work well in many cases.
(defn- load-url
[url args]
(def f (file/popen (string "curl " url)))
(def res (dofile f :source url ;args))
(try (file/close f) ([err] nil))
res)
(defn- check-http-url
[path]
(or (string/has-prefix? "http://" path)
(string/has-prefix? "https://" path)))
# Add the module loader and path tuple to right places
(array/push module/paths ["HTTP" :janet-http check-http-url identity])
(put module/loaders :janet-http load-url)