nginx + lua + template + go

nginx + lua + template + go,第1张

nginx 配置

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    #DNS解析
    resolver 8.8.8.8;
    #是否开通lua编译缓存
    lua_code_cache off;
    #初始化lua模块
    init_by_lua_block {
        --json解析器
        cjson = require "cjson"
        --模板
        template = require 'resty.template'
        --模板缓存,生效需要 lua_code_cache = on 开启
        template.caching(true)
    }
    #
    upstream go_server{  
        server 127.0.0.1:8080;
    }

    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    gzip  on;
    gzip_http_version 1.0;
    #include vhost/*.conf;
    server {
        listen       90;
        server_name  localhost;

        charset utf-8;

        #access_log  logs/host.access.log  main;
        #关闭访问日志 linux
        #access_log /dev/null;
        #关闭访问日志 windows
        access_log \.\nul;

        location / {
            root   site/demo/html;
            index  index.html index.htm;
        }

        location /do
        {
            default_type text/html;
            content_by_lua_file ./site/demo/main.lua;
        }
        set $template_root ./site/demo/tpl;
        location /tpl
        {
            default_type text/html;
            more_set_headers 'Server: N1-G1';
            content_by_lua_file ./site/demo/tpl.lua;
        }
        #代理访问go 服务 
        location ~ /go/(.*) {
           #仅内部访问
           #internal;
           #支持跨域
           add_header Access-Control-Allow-Origin *;
           add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
           add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User- 
           Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
           #代理访问
           proxy_pass   http://go_server/$is_args$args;
           proxy_set_header Host $host;
           proxy_set_header X-Real-IP $remote_addr;
           proxy_set_header REMOTE-HOST $remote_addr;
           proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }  

        error_page  404              /404.html;
        location = /404.html {
            root   html;
        }

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}
tpl.lua
--获取前端的请求方式 
local request_method = ngx.var.request_method

--用于发送到后端数据的对象
local send = {}

-- 参数传递
if "GET" == request_method then
        send.method = ngx.HTTP_GET
        send.args = ngx.req.get_uri_args()
elseif "POST" == request_method then
        ngx.req.read_body()
        send.method = ngx.HTTP_POST
        send.args = ngx.req.get_uri_args()
        --send.body = ngx.req.get_post_args()
        send.body = ngx.req.read_body()
end

--uri
local uri = "/go/" .. string.sub(ngx.var.uri,6,string.len(ngx.var.uri)-1)

--调用后端
local resp = ngx.location.capture(uri, send)
if not resp then  
        ngx.say("request error :", err)  
        return  
end  
--ngx.log(ngx.ERR, tostring(resp.status))  

--获取与设置状态码  
ngx.status = resp.status  

--获取与设置响应头
--[[
for k, v in pairs(resp.header) do  
        if k ~= "Transfer-Encoding" and k ~= "Connection" and k ~= "Content-Type" and k ~= "Content-Encoding" and k ~= "Content-Length" then  
                ngx.header[k] = v  
        end  
end
]]

--获取与设置响应体  
if resp.body then
        local data = cjson.decode(resp.body);
        local func = template.compile("view.html")
        local html = func(data)
        ngx.print(html) 
end
view.html





{<!-- -->{message}}


{{message}}


httpserver.go
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"time"
)

type MainConf struct {
	Addr         string `json:"addr"`
	Readtimeout  int    `json:"readtimeout"`
	Writetimeout int    `json:"writetimeout"`
	Keepalive    bool   `json:"keepalive"`
}

var conf *MainConf

type Result struct {
	r   string
	err error
}

func init() {
	//日志处理
	logFile, err := os.OpenFile("./httpserver.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		fmt.Println("创建日志文件失败:", err)
		return
	}
	log.SetOutput(logFile)
	log.SetFlags(log.Llongfile | log.Ltime | log.LUTC | log.Ldate)
	log.SetPrefix("[HTTP]")

	//配置文件
	buf, err := ioutil.ReadFile("./httpserver.json")
	if err != nil {
		log.Panicln("加载配置文件失败: ", err)
	}
	//conf := MainConf{}
	err = json.Unmarshal(buf, &conf)
	if err != nil {
		log.Panicln("解析配置文件失败:", string(buf), err)
	}
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "hello world")
	})
	mux.HandleFunc("/echo", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, `{"message":"1234"}`)
	})
	mux.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
		ctx, cancel := context.WithTimeout(context.Background(), time.Duration(3)*time.Second)
		defer cancel()
		c := make(chan Result, 1)
		go func() {
			time.Sleep(time.Duration(5) * time.Second)
			pack := Result{r: "ok", err: nil}
			c <- pack
		}()

		select {
		case <-ctx.Done():
			w.Header().Set("state", "Time Out")
			w.WriteHeader(504)
			w.Write([]byte("Time Out\n"))
		case res := <-c:
			fmt.Fprintf(w, res.r)
		}

		//w.Header().Set("name", "my name is smallsoup")
		//w.WriteHeader(504)
		//time.Sleep(time.Duration(5) * time.Second)
		//w.Write([]byte("Internal Server Error\n"))
	})
	serv := &http.Server{
		Addr:         conf.Addr,
		Handler:      mux,
		ReadTimeout:  time.Duration(conf.Readtimeout) * time.Second,  //Wait,TLS handshake,Req. headers,Request body
		WriteTimeout: time.Duration(conf.Writetimeout) * time.Second, //Wait,TLS handshake,Req. headers,Request body,Response,Idle
	}
	serv.SetKeepAlivesEnabled(conf.Keepalive) //HTTP KeepAlive
	err := serv.ListenAndServe()
	if err != nil {
		log.Panicln("启动HTTP服务失败: ", err)
	}
}
httpserver.json
{
    "addr":":8080",
    "readtimeout":3,
    "writetimeout":86400,
    "keepalive":true
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/994266.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存