Common Lisp/外部庫/Hunchentoot
外觀
< Common Lisp | 外部庫
Hunchentoot 是一個用 Common Lisp 編寫的 Web 應用伺服器。
在支援ASDF的系統上安裝Hunchentoot。以下命令將安裝Hunchentoot及其所有依賴項。
(require 'asdf-install)
(asdf-install:install 'hunchentoot)
(asdf:oos 'asdf:load-op :hunchentoot)
(defpackage :testserv
(:use :cl :hunchentoot)
(:export :start-server))
(in-package :testserv)
;; Add a simple prefix dispatcher to the *dispatch-table*
(setq *dispatch-table*
`(,(create-prefix-dispatcher "/hello-world" 'hello-page)))
;; Handler functions either return generated Web pages as strings,
;; or write to the output stream returned by write-headers
(defun hello-page ()
"<html><body>Hello World!</body></html>")
(defun start-server (&key (port 4242))
(start (make-instance 'easy-acceptor :port port)))
啟動伺服器
(testserv:start-server :port 4242)
生成的影像可在 https://:4242/hello-world 訪問。
此示例展示瞭如何使用Vecto[1]生成PNG影像,並使用Hunchentoot提供服務。
第一步:載入外部依賴項
(asdf:oos 'asdf:load-op :hunchentoot)
(asdf:oos 'asdf:load-op :vecto)
第二步:宣告一個包
(defpackage :testserv
(:use :cl :vecto :hunchentoot)
(:export :start-server))
(in-package :testserv)
向*dispatch-table*新增一個簡單的字首分發器
(setq *dispatch-table*
`(,(create-prefix-dispatcher "/img" 'img-page)))
img-page函式期望HTTP引數height包含一個整數值,並生成一個高度為height畫素的PNG影像。如果未指定引數,則使用預設值150。
(defun img-page ()
(setf (content-type*) "image/png")
(let ((out (send-headers)) ; send-headers returns the output flexi-stream
(bar-height (or (and (parameter "height") (parse-integer (parameter "height")))
150)))
(with-canvas (:width 10 :height bar-height)
(rectangle 0 0 10 bar-height)
(set-gradient-fill 0 0
0 1 1 1
0 bar-height
1 0 0 1)
(fill-and-stroke)
(save-png-stream out)))) ; write the image data to the output stream obtained from send-headers
啟動伺服器
(testserv:start-server :port 4242)
生成的影像可在 https://:4242/img 訪問。嘗試更改高度: https://:4242/img?height=350
- http://weitz.de/hunchentoot/ — Hunchentoot 主頁
- http://www.cliki.net/hunchentoot — Common Lisp Wiki 中的 Hunchentoot 條目
- LispCast:用 Common Lisp 編寫簡單的 Reddit 克隆