ACF mvc.lua example
Set the hostname with mvc.lua
In this example we will create a simple hostname-setting command-line application using mvc.lua. Once the controller/model are built, you can use the same code to set the hostname via the web with a web-based application controller.
For this example, we will assume you have root access on the linux box you are running on (preferably an alpine box!)
Get the mvc.lua module
svn "export" the mvc.lua module. Export will grab a copy without all the extra hidden "version control" stuff
svn export svn://svn.alpinelinux.org/acf/core/trunk/www/cgi-bin/mvc.lua
Create a model and controller
Create a file hostname-model.lua, defining the module functions to set and read the hostname. We return a table for each function including the value, error message and type of the value ("String" in the case of the hostname).
hostname-model.lua
-- Model functions for retrieving / setting the hostname module ( ..., package.seeall ) -- All functions return a table with -- A value, the type of the value, and a message if there was an error local hosttype={ type="string" } update= function ( name ) -- Check to make sure the name is valid if (name == nil) then hosttype.msg = "Hostname cannot be nil" elseif (#name > 16) then hosttype.msg = "Hostname must be less than 16 chars" elseif (string.find(name, "[^%w%_%-]")) then hosttype.msg = "Hostname can contain alphanumerics only" end -- If it is, set the hostname if (hosttype.msg == nil ) then local f = io.open("/etc/hostname", "w") if f then f:write(name) f:close() end f = io.popen ("/bin/hostname -F /etc/hostname") f:close() return read() -- Otherwise, return the error message else hosttype.value = name return hosttype end end read= function () local f = io.popen ("/bin/hostname") local n = f:read("*a") or "none" f:close()
Create a file hostname-controller.lua, defining the functions that an "end user" could run. We define Create Read Update Delete as standard actions:
hostname-controller.lua
-- hostname controller code module ( ... , package.seeall ) create = function (self, name ) return self.model.update(name) end read = function (self) return self.model.read() end update = function (self, name ) return self:create(name) end delete = function (self, name) return self:create("") end
Optionally test the model code (without mvc.lua)
If you want, you can create a test.lua script to validate the model code works on its own:
test.lua
m=require("hostname-model") print(m.update(arg[1]).msg) print(m.read().value)
You can then test this with:
#lua test.lua "Alpine" nil Alpine
#lua test.lua "Invalid Name" Hostname can contain alphanumerics only Alpine