|
20 | 20 | require 'rack' |
21 | 21 | require 'sqlite3' |
22 | 22 |
|
| 23 | +begin; require 'glug' # Optional glug dependency |
| 24 | +rescue LoadError; end # | |
| 25 | + |
23 | 26 | db = SQLite3::Database.new(ARGV[0]) |
24 | 27 | content_types = { |
25 | 28 | json: "application/json", |
26 | | - png: "image/png" |
| 29 | + png: "image/png", |
| 30 | + pbf: "application/octet-stream" |
27 | 31 | } |
28 | 32 |
|
29 | 33 | app = Proc.new do |env| |
30 | 34 | path = env['REQUEST_PATH'].sub(/^\//,'') |
| 35 | + |
31 | 36 | if path =~ %r!/(\d+)/(\d+)/(\d+).*\.pbf! |
| 37 | + # Serve .pbf tile from mbtiles |
32 | 38 | z,x,y = $1.to_i, $2.to_i, $3.to_i |
33 | 39 | tms_y = 2**z - y - 1 |
34 | 40 | res = db.execute("SELECT tile_data FROM tiles WHERE zoom_level=? AND tile_column=? AND tile_row=?", [z, x, tms_y]) |
35 | 41 | if res.length>0 |
36 | 42 | puts "Serving #{z}/#{x}/#{y}" |
37 | 43 | blob = res[0][0] |
38 | | - ['200', {'Content-Type'=>'application/x-protobuf', 'Content-Encoding'=>'gzip'}, [blob]] |
| 44 | + ['200', {'Content-Type'=>'application/x-protobuf', 'Content-Encoding'=>'gzip', 'Content-Length'=>blob.bytesize.to_s }, [blob]] |
39 | 45 | else |
40 | 46 | puts "Empty #{z}/#{x}/#{y}" |
41 | | - ['200', {'Content-Type'=>'application/x-protobuf' }, []] |
| 47 | + ['200', {'Content-Type'=>'application/x-protobuf', 'Content-Length'=>'0' }, []] |
42 | 48 | end |
| 49 | + |
43 | 50 | elsif ARGV.include?(path) |
| 51 | + # Serve static file |
44 | 52 | ct = path.match(/\.(\w+)$/) ? (content_types[$1.to_sym] || 'text/html') : 'text/html' |
45 | 53 | ['200', {'Content-Type' => ct}, [File.read(path)]] |
| 54 | + |
| 55 | + elsif ARGV.include?(path.sub(/\.json$/,'.glug')) |
| 56 | + # Convert .glug style to .json |
| 57 | + glug = Glug::Stylesheet.new { instance_eval(File.read( path.sub(/\.json$/,'.glug') )) }.to_json |
| 58 | + ['200', {'Content-Type' => 'application/json' }, [glug] ] |
| 59 | + |
46 | 60 | else |
| 61 | + # Not found |
47 | 62 | ['404', {'Content-Type' => 'text/html'}, ["Resource at #{path} not found"]] |
48 | 63 | end |
49 | 64 | end |
|
0 commit comments