nginx+lua(openresty) 登陆服务器(二)

** 前言**
前章讲述了最基本的功能,这章深化下,以此做个login server

1: lua 代码
http.lua

local function getrealip()
	local headers=ngx.req.get_headers()
   local ip=headers["X-REAL-IP"] or headers["X_FORWARDED_FOR"] or ngx.var.remote_addr or "0.0.0.0"
    return ip
end

local function main()
	local realip =  getrealip()
	ngx.say("realip:",realip)
	--ngx.say("http.lua_4")
    
   
   local arg = ngx.req.get_uri_args()
   local uid = arg["uid"]
   local token = arg["token"]
	local PRODUCTCODE =  'testplatformhahah'

    --local HTTPREQ =require ".http_req"  --
  local httpreq = require "http_req"
  local reqUrl = "http://127.0.0.1:10009"
	 
	local reqBody ={
    
    
	['uid']=uid,
	['token']=token,
	['product_code']=PRODUCTCODE
	}
	
	local cjson= require("cjson"); --加载cjson模块
	local bodystr = cjson.encode(reqBody)
	local bodystrlen = #bodystr
	
	local reqHeaders = {
    
      
        ["Content-Type"]= "application/json",
		["Content-Length"] = ""..bodystrlen
    } 
	
	--http://127.0.0.1:9002/testlua?uid=12345&token=%27edcvfrtgb5678%27
	
	------200 ok
	--headers={"Content-Type":"application\/json;charset=utf-8","Content-Length":"135","Access-Control-Allow-Headers":"Content-Type","Date":"Fri, 09 Jun 2023 08:11:07 GMT","Access-Control-Allow-Origin":"*"}135
---body=content type: application/json, get request:{"product_code":"82842161214681785932999998977015","uid":"12345","token":"'edcvfrtgb5678'"}
--content type: application/json, get request: 44byte length +91 = 135
--body={"result":1,"halladdr":"192.168.1.2","param1":12345}
    local reqResult,reqErr = httpreq.http_post(reqUrl,reqHeaders,bodystr,30000);  --- reqErr
	if reqResult  then 
		if(reqResult.status==200) then
			--ngx.say("200 ok")
			local headersstr = cjson.encode(reqResult.headers)
			ngx.say("headers=",headersstr," Content-Length=",reqResult.headers["Content-Length"])
			if reqResult.body then
				ngx.say("body=",reqResult.body)
			end
			return 
		else
			ngx.say("fail status=",reqResult.status)	
		end
	else
	    ngx.say("fail reason=",reqErr or "unknow reason")	
	end
	
	--ngx.say("fail0 len=",bodystrlen)
	
end
main()
--http://127.0.0.1:9002/testlua?uid=12345&token='edcvfrtgb5678'
--ngx.exit 立即中断当前http请求,后续lua代码将不会再执行,底层socket通道还存在,
--只要没超过保活时间,如果用了proxypass做子请求,不影响
--ngx.eof 立即中断当前http请求,后续的lua代码将继续执行,底层socket通道也立即断开,
--如果用了proxypass做子请求,子请求也会断开。
--ngx.timer.at 这个是nginx提供的轻线程,主要做后台任务执行用,一般和ngx.exit配合使用

http_req.lua 参考了网上别人的

local myHttp = require "resty.http"
---Get 请求
local function _http_get(url,headerParm,timeout)
    local httpc = myHttp.new();
    timeout = timeout or 30000;
    httpc:set_timeout(timeout)
    local res, err_ = httpc:request_uri(url, {
    
    
        method = "GET",
        keepalive=false,
        headers = headerParm;
    })
    httpc:set_keepalive(5000, 100);
    ---httpc:close();
    return res,err_;
end
---Post 请求
local function _http_post(url,headerParm,body,timeout)
    local httpc = myHttp.new();
    timeout = timeout or 30000;
    httpc:set_timeout(timeout);
    local res, err_ = httpc:request_uri(url, {
    
    
        method = "POST",
        body = body,
        keepalive=false,
        headers =  headerParm;
    })
    httpc:set_keepalive(5000, 100)
    ---httpc:close();
    return res,err_;
end


return {
    
    
http_get = _http_get,
http_post = _http_post
}

2:模拟平台代码
这里以golang 随便写了个
关键代码如下

func clientfun(w http.ResponseWriter, r *http.Request) {
    
    

	r.ParseForm()

	path := r.URL.Path
	remoteip := RetmoteIp(r)
	log.Printf("path =%v remoteip=%v \n", path, remoteip)

	log.Printf("Get %s request. host: %s  params: %s\n", r.Method, r.Host)
	len := r.ContentLength
	rtype := r.Header.Get("Content-Type")
	content := make([]byte, len)
	r.Body.Read(content)
	fmt.Println("request-type: ", rtype)
	fmt.Println("request-lenght: ", len)
	fmt.Println("request-content: ", string(content))
	setkuayu(w)
	//fmt.Fprintf(w, "content type: %s, get request:%s", rtype, string(content))
	v := &JsonLoginResult{
    
    }
	v.Result = 1
	v.HallAddr = "192.168.1.2"
	v.Param1 = 12345
	sendJson(w, v)
	
}

3: 测试
浏览器 请求到nginx 执行 http.lua ,http.lua 请求平台 再返回
相当于 前端 -->登陆服务器->平台 验证 token
在这里插入图片描述
4:后续
以此为基础,增加gate 负载均衡

如果觉得有用,麻烦点个赞,加个收藏

猜你喜欢

转载自blog.csdn.net/yunteng521/article/details/131130525