jialiguo 发表于 2016-12-28 06:45:04

40行代码完成c代码高亮的移动版(nginx的rewrite)

ios和android没有给力的看代码的工具
有时候想赖床上看代码感觉麻烦
不如自己弄一个最简单的代码高亮,被窝里用手机pad神马的看代码,还能高亮显示
使用chrome吧,
1个html和nginx的一小段配置,实现代码阅读
不用任何代码生成工具,什么转化之类的都不用
nginx/nginx.conf中加入

server {
autoindex on;
listen 8080;
location ~ \.c$ {
rewrite ^ http://localhost/code.html?aa=$uri;
}
}

1.autoindex on;
是让nginx可以访问目录下的文件的
2.所有.c的文件全都跳转到新的这个链接
3.新的这个链接处理$uri,通过ajax写到html中,用prettify.js解析成高亮的,
注意js要放到最后,在jquery解析之后加载高亮
4.如果java神马的就把.c改成.java,或其他的
html的代码为
nginx/html/code.html

<html>
<head>
<link href="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
var url = document.location.href;
var realurl="";
if (url.indexOf("=")>0){
realurl = url.substring(url.indexOf("=")+1,url.length);
}
$.ajax({
type: 'GET',
url: realurl,
success: function(data){
data=data.replace(/</g,"&lt;").replace(/>/g,"&gt;");
$("#thiscode").html(data);
},
error:function(e){
alert("error:"+e);
},
dataType: "string"
});
</script>
<pre class="prettyprint" id="thiscode">
</pre>
</body>
</html>
<script src="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js" type="text/javascript"></script>

注意要用GET,
POST会导致405,还得处理
搞定
测试
随便
把一个源码目录扔到
nginx/html/下就行了
比如把nginx的src目录扔进来

然后访问
http://localhost:8080/src
点任何一个.c都会跳到http://localhost/code.html?aa=b.c




完整的nginx-1.3.4/conf/nginx.conf为
只加了第10到第16行,注释去掉了

worker_processes4;
events {
worker_connections1024;
}
http {
include       mime.types;
default_typeapplication/octet-stream;
sendfile      on;
keepalive_timeout65;
server {
autoindex on;
listen 8080;
location ~ \.c$ {
rewrite ^ http://106.187.88.34/code.html?aa=$uri;
}
location / {
root   html;
indexindex.html index.htm;
}
}
server {
listen       80;
server_namelocalhost;
location / {
root   html;
indexindex.html index.htm;
}
error_page   500 502 503 504/50x.html;
location = /50x.html {
root   html;
}
}
}



后记:
开始有bug,<>中的东西全被html解析成标签了,显示不了,
中间加了一行,搞定
data=data.replace(/</g,"&lt;").replace(/>/g,"&gt;");
ie显示的时候没有换行
opera打不开
firefox和chrome没问题
其实感觉跟jsp的过滤器也能实现,就是感觉nginx的rewrite好玩
页: [1]
查看完整版本: 40行代码完成c代码高亮的移动版(nginx的rewrite)