CF web 中间件开发指南

2019-04-02 11:28 更新

介绍

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

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

中间件设计方法

[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进行测试后发现, 第一个路由被禁止访问, 第二个路由正确返回. :)

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号