解析nginx配置文件 nginx-java-parser

Nginx configuration Java parser

解析nginx配置文件,并將nginx配置文件格式化成對象,方便java程序管理nginx配置。解析配置文件并非使用正則匹配,而是使用語法分析樹處理解決的。
This library helps in analyzing Nginx web server configuration files, looking up for specified parameters, blocks, regular expressions or comments. Then AST can be modified and converted back to plain file.

Features

  • Convert config file to AST tree using ANTLR4 parsing capabilities
  • The same is available for JavaCC too (deprecated)
  • Rebuild config files and dump them back to *.conf
  • Nested blocks support
  • If statements support
  • Unquoted regexp within location/rewrite/if statements support
  • Comments support

Installation

Add the following dependency to your POM:

<dependency>
    <groupId>com.github.odiszapc</groupId>
    <artifactId>nginxparser</artifactId>
    <version>0.9.3</version>
</dependency>

Examples

Parser

How to perform basic parsing of the following Nginx config:

NgxConfig conf = NgxConfig.read("/etc/nginx/nginx.conf");
NgxParam workers = conf.findParam("worker_processes");       // Ex.1
workers.getValue(); // "1"
NgxParam listen = conf.findParam("http", "server", "listen"); // Ex.2
listen.getValue(); // "8889"
List<NgxEntry> rtmpServers = conf.findAll(NgxConfig.BLOCK, "rtmp", "server"); // Ex.3
for (NgxEntry entry : rtmpServers) {
    ((NgxBlock)entry).getName(); // "server"
    ((NgxBlock)entry).findParam("application", "live"); // "on" for the first iter, "off" for the second one
}

/etc/nginx/nginx.conf:

worker_processes  1;            # <- Ex.1

http {
    server {
        listen       8889;      # <- Ex.2
        server_name  localhost;
    }
}

rtmp {
    server {                    # <- Ex.3 (first)
        listen 1935;
        application myapp {
            live on;
        }
    }

    server {                    # <- Ex.3 (second)
        listen 1936;
        application myapp2 {
            live off;
        }
    }
}
Dumper
NgxConfig conf = NgxConfig.read("/etc/nginx/nginx.conf");
// ...
NgxDumper dumper = new NgxDumper(conf);
return dumper.dump(System.out);

Authors

Alexey Plotnik (odiszapc@gmail.com, http://推ter.com/odiszapc, http://alexey-plotnik.me) I do it just because I like it.

License

Apache 2.0

項目地址: https://github.com/odiszapc/nginx-java-parser

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!