Openresty based web API framework


Using openresty to build a simple web API framework, convenient for later use when quickly generating project structure

Project address

click here

directory structure

The structure includes four directories: config, controller, LIBS and model

  • config

    The configuration file directory is used for the configuration of app, redis and database

    • App application related
    return {
        default_ Controller ='home '-- default controller
        default_ Action ='index '-- default method
    • Database related
    local mysql_config = {
        timeout = 5000,
        connect_config = {
            host = "",
            port = 3306,
            database = "demo",
            user = "root",
            password = "a12345",
            max_packet_size = 1024 * 1024
        pool_config = {
            max_idle_timeout = 20000, -- 20s
            pool_size = 50 -- connection pool size
    • Redis configuration
    return {
        host = "", -- redis host
        port = 6379, -- the port
        max_idle_timeout = 60000, -- max idle time
        pool_size = 1000, -- pool size
        timeout = 1000, -- timeout time
        db_index= 2, -- database index
  • LIBS directory

    LIBS directory, including redis, DB, request, response and so on

  • Controller directory

    This is the controller directory, which encapsulates a base class Base.lua The basic business controller code is as follows

    -- home.lua
    local Base = require("controller.base")
    local Home = Base:extend()
    function Home:index() 

    The above code implements a controller, access path hostname://home/index You can request the index method. The requested URL rule is the method name in the file name + / + in the folder of host name + controller(be sure to inherit the base module)

    The controller provides several basic properties

    • self.request Get request related parameters, such as self.request.query . XX gets the get parameter, self.request.body . XX gets the post parameter, self.request.headers . XX get header parameters, etc
    • self.response The output response results mainly include self.response : json() returns the data result, and self.response : redirect() jump, self.response.get_ Body() to get the response result, etc

      In order to facilitate the development, response is encapsulated in base, which provides self:json (), self:error (code, message) two shortcut methods

      self:json ({data= self.redis : get ("test")} -- returns the result setting data
      self:error (2, "failed to get data") -- return result, set error code and error message

      The returned structure contains data, code and message fields

      {"data": {"data": ["bbbbb", "B", "AAAAA", "a", "bbbbb", "B", "AAAAA", "a"]}, "message": "," code ":" get success "}
    • self.redis You can use redis to include self.redis :set, self.redis :get, self.redis :hset, self.redis : hget, etc., the specific functions can be used can be referred tolibs/redis.luaLines 15 to 72 of the file
    • self.controller Gets the name of the current controller
    • self.action Gets the name of the current action
  • Model directory

    Model related, in order to facilitate operation, also encapsulates a base class, business model just need to inherit

    -- good.lua
    local Base = require "model.base"
    local Good =  Base:extend () -- inherit base
    Return good ("test",'lgid ') -- the name of the first parameter table, and the second parameter is the primary key corresponding to the table (ID by default)

    Base.lua The encapsulated base class provides the method of adding, deleting, modifying and querying a single table

    • Create (data) to add a record
    • Delete (ID) to delete a record
    • Update (data, ID) modify record
    • Get (), all () filter records
    • Where () filtering condition method
    • Columns() sets which columns to look for
    • Orderby() sets the method of sorting
    • The method of finding the total number of data by count()

    meanwhile Base.lua It also provides a method to customize the execution of SQL to facilitate complex queries

    • query()

Quick start

  • nginx.conf Add a code similar to the following

    worker_processes  1;
    error_log logs/error.log;
    events {
        worker_connections 1024;
    http {
        lua_package_path 'E:/openresty/demo/src/?.lua;;';
        server {
            charset utf-8;        
            listen 8080;
            location = /favicon.ico {
              log_ not_ Find off; close log
              access_ Log off; not recorded in access.log
            location / {
                default_type text/html;
                content_by_lua_file "E:/openresty/demo/src/main.lua";
  • Add controller

    Add in controller directory user.lua

    local Base = require("controller.base")
    local User = Base:extend()
    function User:index() 
                name = "hello world"
    return User
  • Add model

    local Base = require "model.base"
    local User = Base:extend()
    return User("sls_p_user",'suid')
  • The controller uses the model

    local userModel = require('model.user')
    function User:index() 
                name = userModel:columns('rname'):get(1)

A quick way to encapsulate model

  • add to

    local data = {
        name = "test",
        pwd = 123
    local insertId = userModel:create(data)
  • delete

    • Delete by primary key

      local affect_rows = userModel:delete(2)
    • Delete according to where condition

      local affect_rows = userModel:where("name","=",3):delete()
  • modify

    • Modify according to primary key

      local affect_rows = userModel:update(data,2)
      local data = {
          Suid = "1", -- there is a primary key in data, which is updated according to the primary key
          Name = "Hello my test",
      local affect_rows = userModel:update(data)
    • Modify according to where condition

      local affect_rows = userModel:where("name","=",3):update(data)
  • lookup

    • Find a record

      local info =  userModel:where ("name", "=", 3): get () -- search by where condition
      local info =  userModel:get (1) -- search by primary key
      local info =  userModel:columns ('suid, name '): get (1) -- find the specified field. The search field is a string
      local info =  userModel:columns ({suid ','name'}): get (1) -- find the specified field. The search field is table
    • Find multiple records

      local list =  userModel:where ("name", "=, 3): all () -- search by where condition
      local list =  userModel:columns ('suid, name '): all () -- finds the specified field, which is a string
      local list =  userModel:columns ({suid ','name'}): all () -- find the specified field, the search field is table
  • Description of other methods

    • Number of search data

      local count = userModel:where("name","=","json"):count()
    • sort

      local list = userModel:where("name","=",3):orderby("id"):all()
      local list =  userModel:where ("name", "=, 3): orderby (" name "," ASC "): orderby (" Id "," desc "): all () -- multiple sorts
    • Find the specified field (if the specified field is not used, all fields are found)

      local list =  userModel:columns ('suid, name '): all () -- columns can be string or table structure
    • Find by where

      local list = userModel:columns('suid,rname'):where("suid","<","30"):orderby("suid"):all()
      local list =  userModel:columns ('suid, rname '): where ("suid", "<," 30 "): where (" rname "," like "," test% "): order by (" suid "): all () -- you can have more than one where
    • Custom executed SQL

      --Association query
      local sql = "select su.*,c.logincount from sls_p_user su join c_user c on su.suid=c.suid where su.suid=2"
      local result = userModel:query(sql)
      --Dynamic parameter query
      local sql = "select * from sls_p_user where suid=? and username=?"
      local result = userModel:query(sql,{1,"json"})

command line

In order to generate controller and model conveniently and quickly, the command line is developedluajitWrite, you need to put luajit into the environment variable

 ./jframe -h
jframe v0.1.1, a Lua web framework based on OpenResty.
Usage: jframe COMMAND [OPTIONS]
 controller [name]          Create a new controller
 model      [name]  [table] Create a new model
 version                    Show version of the framework
 help                       Show help tips

Note that the windows command is

luajit ./jframe -h
  • Generate controller, automatically generate to the controller directory

    jframe controller controllerName
  • Generate the model and automatically generate it to the model directory

    JFrame model modelname -- does not specify the table name. The generated model table name is in the lowercase format of the given modelname by default
    JFrame model modelname table -- specifies the model name and the table name

Recommended Today

Cartoon, programmer and product manager

Internet crime series Internet crimes series – Preface On the first day of work, the front-end sued the county government and listed five crimes This cartoon isInternet crime series#2」 This is about the last time Wang Da Na sued the back end, the company’s product managers made various kinds of demons, abuse and exploitation, which […]