codecamp

CF web 中间件开发指南

介绍

中间件的设计得益于项目分层设计模式, 其作用是为了将不同作用的代码分离.

中间件设计能方便用户更加简洁高效的管理自己的项目.

中间件设计方法

[httpd](https://github.com/CandyMi/core_framework/wiki/httpd)库提供了一个```before```函数, 用于在每次请求被用户处理之前优先调用.

以下为抛砖引玉, 提供了一种最简单的中间件设计示例:

  local httpd = require "httpd"
  local http = require "http"


  local app = httpd:new('httpd')


  app:before(function(content)
    if string.find(content.path, '^/admin+') then
      return http.throw(401, '<h1>验证失败</h1>')
    end
    return http.ok()
  end)


  app:api('/admin/login', function(content)
    return '{"code":200,"message":"ok"}' -- json string
  end)


  app:api('/api/login', function(content)
    return '{"code":200,"message":"ok"}' -- json string
  end)


  app:listen("0.0.0.0", 8080)
  app:run()

测试

使用curl进行测试后发现, 第一个路由被禁止访问, 第二个路由正确返回. :)

CF web Websocket应用指南
CF 使用Dockerfile构建开发环境
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

API 使用手册

HTTP API

Mail API

DB API

DB

Cache API

class API

MQ API

MQ

Crypt API

cf API

cf

System API

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }