A Rate-Limiting HTTP Proxy(4)HTTP MVC

ARate-LimitingHTTPProxy(4)HTTPMVC

HTTP

ThereareseveralHTTPhandlingmethod

Proxy-nginxworkasanProxy

location~^/user{

proxy_passhttp://127.0.0.1:8080;

}

ItrytomakeNGINXrunningon80port,butIgetthiserrormessage:

[emerg]73020#2236172:bind()to0.0.0.0:80failed(13:Permissiondenied)

Addthistothenginx.conf,restartitwithsudoer

userroot;

Exception:

nginx:[emerg]getgrnam("root")failedin/opt/luaweb/conf/nginx.conf:1

Solution:

http://blog.csdn.net/u013091013/article/details/51860303

Ishouldasthislinetothetop.

userrootowner;

AddHTMLEditortomyEclipse,addthisURLtothepluginlisthttp://download.eclipse.org/releases/mars/-onlyselecttheHTMLeditorandJSeditor

Hereisthewholescript-nginx.conf

userrootowner;

worker_processes1;

error_loglogs/error.lognotice;

events{

worker_connections1024;

}

http{

server{

listen80;

location/{

roothtml;

indexindex.html;

}

location~^/user{

proxy_passhttp://localhost:8080;

}

}

lua_package_path"/opt/luaweb/lua/?.lua;;";

server{

listen8080;

lua_code_cacheoff;

location~/user/(.+){

default_typetext/html;

content_by_lua_filelua/$1.lua;

}

}

}

index.htmlpagetoShowtheLookandFeel

<html>

<head>

<metacharset="UTF-8">

<title>LoginPage</title>

</head>

<body>

UserName:<inputtype="text"id="username"value="admin">

Password:<inputtype="password"id="password"value="admin">

<ahref="javascript:void(0)"onclick="login()">Login</a>

<scriptsrc="//cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>

<script>

functionlogin(){

varusername=$('#username').val();

varpassword=$('#password').val();

$.post('/user/login',{username:username,password:password},function(res){

console.log(res)

varmsg=res.ret?"登录成功":"登录失败"

alert(msg)

},'json')

}

</script>

</body>

</html>

HeretheLUAScripttohandletheLogin,thatcanbeJAVA,PYTHONoranyOtherBackend.

lua/login.luamocktheBackendLogic

localreq=require"req"

localcjson=require"cjson"

localargs=req.getArgs()

localusername=args['username']

localpassword=args['password']

localres={}

ifusername=="admin"andpassword=="admin"then

res['ret']=true

res['token']=ngx.md5('admin/'..tostring(ngx.time()))

else

res['ret']=false

end

Modulengx.location.capture

Wecandosomethingontheparamslevel.

localreq=require“req”

localargs=req.getArgs()

GET

localres=ngx.location.capture(‘/user/login’,{method=ngx.HTTP_GET,args=args,});

POST

localres=ngx.location.capture(‘/user/login’,{method=ngx.HTTP_POST,body=ngx.encode_args(args),});

ExceptionifwedoGETwithoutPostBody

norequestbodyfound;maybeyoushouldturnonlua_need_request_body?

Solution:

ThatisbecausetheHTTPmethodisnotmatchinthejQuery.IfitisusingGET,thenluashouldbeGET,orPOSTtogether.

Hereisthefinallocal-login.lua

localreq=require"req"

localcjson=require"cjson"

localargs=req.getArgs()

--GET

localres=ngx.location.capture('http://localhost/user/login',{method=ngx.HTTP_GET,args=args})

--POST

--localres=ngx.location.capture('/user/login',{method=ngx.HTTP_POST,body=ngx.encode_args(args)})

--print(res.status)--statuscode

ifres.status==200then

localret=cjson.decode(res.body)

ret['from']='local'

ngx.say(cjson.encode(ret))

else

print(res.body)

ngx.say('{"ret":false,"from":"local"}')

end

HTMLbuttonandcommandinindex.html

<ahref="javascript:void(0)"onclick="local_login()">LocalLogin</a>

functionlocal_login(){

varusername=$('#username').val();

varpassword=$('#password').val();

$.get('/user/local-login',{username:username,password:password},function(res){

console.log(res)

varmsg=res.ret?"本地登录成功":"本地登录失败"

alert(msg)

},'json')

}

ThirdPartyModulelua-resty-http

https://github.com/pintsized/lua-resty-http

Exception:

2017/05/1813:48:18[error]19934#2742039:*53luaentrythreadaborted:runtimeerror:/opt/luaweb/lua/local-login.lua:3:module'resty.http'notfound:

Solution:

https://moonbingbing.gitbooks.io/openresty-best-practices/ngx_lua/how_use_third_lib.html

Copytheluamodulescriptinopenresty

>cp~/Downloads/lua-resty-http-master/lib/resty/*.lua./

Updatedlocal-login.luatosupportThirdParty

localreq=require"req"

localcjson=require"cjson"

localhttp=require"resty.http"

localargs=req.getArgs()

--GET

--localres=ngx.location.capture('http://localhost/user/login',{method=ngx.HTTP_GET,args=args})

--POST

--localres=ngx.location.capture('/user/login',{method=ngx.HTTP_POST,body=ngx.encode_args(args)})

--http

localhttpc=http.new()

localres=httpc:request_uri("http://127.0.0.1:8080/user/login",{

method="POST",

body=ngx.encode_args(args),

headers={

["Accept"]="application/json",

["Accept-Encoding"]="utf-8",

["Cookie"]=ngx.req.get_headers()['Cookie'],

["Content-Type"]="application/x-www-form-urlencoded",

}

})

httpc:set_keepalive(60)

--print(res.status)--statuscode

DispatherServlet—MVC

https://github.com/362228416/openresty-web-dev/tree/master/demo8

nginx.conf

http{

lua_package_path"$prefix/lua/?.lua;$prefix/lualib/?.lua;;";

server{

listen80;

server_namelocalhost;

lua_code_cacheoff;

location/{

default_type"text/html;charset=utf-8";

content_by_lua_filelualib/lite/mvc.lua;

}

location~^/js/|^/css/|\.html{

roothtml;

}

}

}

lualib/lite/mvc.luaishandlethemoduleName/methodName

localuri=ngx.var.uri

--homepage

ifuri==""oruri=="/"then

localres=ngx.location.capture("/index.html",{})

ngx.say(res.body)

return

end

localm,err=ngx.re.match(uri,"([a-zA-Z0-9-]+)/*([a-zA-Z0-9-]+)*")

localis_debug=true

localmoduleName=m[1]--module

localmethod=m[2]--method

ifnotmethodthen

method="index"--defaultmethodindex

else

method=ngx.re.gsub(method,"-","_")

end

--controllerisunderweb

localprefix="web."

localpath=prefix..moduleName

--inputthemoduleweb.user

localret,ctrl,err=pcall(require,path)

ifret==falsethen

ifis_debugthen

ngx.status=404

ngx.say("<pstyle='font-size:50px'>Error:<spanstyle='color:red'>"..ctrl.."</span>modulenotfound!</p>")

end

ngx.exit(404)

end

--methodofthemodule,get,index

localreq_method=ctrl[method]

ifreq_method==nilthen

ifis_debugthen

ngx.status=404

ngx.say("<pstyle='font-size:50px'>Error:<spanstyle='color:red'>"..method.."()</span>methodnotfoundin<spanstyle='color:red'>"..moduleName.."</span>luamodule!</p>")

end

ngx.exit(404)

end

--callluamethod

ret,err=pcall(req_method)

ifret==falsethen

ifis_debugthen

ngx.status=404

ngx.say("<pstyle='font-size:50px'>Error:<spanstyle='color:red'>"..err.."</span></p>")

else

ngx.exit(500)

end

end

2Methodsinlua/web/user.lua

localcjson=require"cjson"

localreq=require"lite.req"

local_M={}

localusers={"MrLi","MrLuo","MrKang"}

function_M.index()

ngx.say(cjson.encode(users))

end

function_M.get()

localargs=req.getArgs()

localindex=tonumber(args['index'])

ifnotindexthen

index=1

end

ngx.say(users[index])

end

return_M

WecanvisitpageURLlikethis

http://localhost/user—lua/web/user.luamethodindex

http://localhost/user/get?index=1—lua/web/user.luamethodget

HomePageindex.htmlandindex.jsindex.cssareasfollow:

<html>

<head>

<metacharset="UTF-8">

<title>HomePage</title>

<linkrel="stylesheet"href="/css/index.css">

</head>

<body>

<divclass="container">

<h1>UserLists</h1>

<ulid="users"></ul>

<p>Second<spanid="user"></span></p>

</div>

<scriptsrc="//cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>

<scriptsrc="/js/index.js"></script>

</body>

</html>

.container{

width:1000px;

margin:0auto;

text-align:center;

}

(function(){

$.getJSON('/user/',function(data){

$('#users').html(data.join(','))

console.log(data)

})

$.get('/user/get',{index:2},function(data){

$('#user').html(data)

console.log(data)

})

})()

References:

https://github.com/362228416/openresty-web-dev/tree/master/demo7

https://moonbingbing.gitbooks.io/openresty-best-practices/

相关推荐