Chinaunix首页 | 论坛 | 博客
  • 博客访问: 629525
  • 博文数量: 37
  • 博客积分: 106
  • 博客等级: 民兵
  • 技术积分: 993
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-30 18:26
个人简介

来自汉江北邻的IT男一枚,专注于PHP和C#开发... 最常更新的技术Blog → https://enjoy233.cnblogs.com/

文章分类

全部博文(37)

文章存档

2013年(36)

2012年(1)

我的朋友

分类: 高性能计算

2013-04-15 18:22:03


                                                 用 Emacs Lisp 开发 CGI 程序


Emacs Lisp 作为编程语言也是非常强大的尤其 Emacs 作为一款编辑器,自带了很多处理文本的函数,用起来很方便我一直希望用 Emacs Lisp 作为服务端脚本语言来开发 Web 程序。在网上搜索了很久,还真有人做过类似的事情:.el。但他封装的还不够彻底,用起来还是挺麻烦,于是自己动手写了一个目前支持:

  1. script-let,即可在 <% %> 或 <%= %> 之中插入 lisp 代码;
  2. 原生 s-exp 生成 html 文档;
  3. GET/POST 请求支持;
  4. 存取 Cookie

程序作为 CGI 运行于 Apache 下,这里提供一个简单的求斐波那契数的例程作为演示

BTW,这也是我第一次使用 Github 托管代码:

#!/usr/local/bin/emacs --script

(require 'cgi)

(cgi/cookie "n"
 (or (cgi/param "n")
     (cgi/cookie "n")
     "15"))

(html
 (head
  (title "Fabonacci 1 -> n")
  (meta (http-equiv . "Content-Type")
        (content . "text/html; charset=UTF-8")))
 (body
  (form (method . post)
   (span "n = ")
   (input (type . text) (name . n))
   (button (type . submit) "Submit"))
  (table (border . 1) (width . "100%")
   (thead
    (caption "Fabonacci")
    (tr
     (th "#")
     (th "Value")))
   (tbody
    <%
    (let ((a 0) (b 1) x)
      (dotimes (i (string-to-number
                   (cgi/cookie "n")))
        (tr
         (td <%= (1+ i) %>)
         (td <%= (setq x a a b b (+ x b)) %>))))
    %>))))

运行效果:



2012-09-03 19:16

最新进展:Emacs-cgi 加入对存取 Cookie 和 Session 的支持,以及页面之间跳转(redirect和forward)项目地址:下面以一个登入页面作为示例:

首先是首页:如果用户为登入,显示输入框提示用户输入用户名;否则输出欢迎词

#!/usr/local/bin/elisp

(require 'cgi)

(html
 (head
  (title "Hello Session")
  (meta (http-equiv . "Content-Type")
        (content . "text/html; charset=UTF-8")))
 (body
  (h1 "Welcome to Emacs Lisp CGI")
   <%
   (if (cgi/session "name")
       (form (method . post) (action . "logout.el")
        (div
         "Hello " <%= (cgi/session "name") %>
         (button (type . submit) logout)))
     (form (method . post) (action . "login.el")
      (div
       "My name is: "
       (input (type . text)
              (name . name))
       (button (type . submit) Submit))))
   %>)))

然后登入处理页面,在 session 中设置名字

#!/usr/local/bin/elisp

(require 'cgi)

(if (cgi/param "name")
    (cgi/session "name" (cgi/param "name")))
(cgi/redirect "index.el")

最后是退出处理页面,即清空 session 中的值

#!/usr/local/bin/elisp

(require 'cgi)

(cgi/remove-session "name")
(cgi/redirect "index.el")

运行效果:





 
阅读(2270) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~