Created
March 3, 2014 15:19
-
-
Save kimh/9327181 to your computer and use it in GitHub Desktop.
Accessing filesystem with REST api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'sinatra/base' | |
module Sensive | |
class DocServer < Sinatra::Base | |
def self.run!(params={}) | |
super | |
end | |
basedir = "./data" | |
dirs = Dir.glob("#{basedir}/*/*") | |
#GET /data/passwords/*/value | |
dirs.each do |path| | |
url = path[1..-1] | |
puts "Define: GET #{url}" | |
get "#{url}" do | |
file = File.join(path, "value") | |
File.open(file) do |f| | |
f.read | |
end | |
end | |
end | |
#POST /data/passwords/*/value | |
dirs.each do |path| | |
url = path[1..-1] | |
parent_dir = url.split("/")[0..-2].join("/") | |
puts "Define: POST #{parent_dir}/:name" | |
post "#{parent_dir}/:name" do | |
value = params["value"] | |
dir = File.join("./", parent_dir, params[:name]) | |
if Dir.exists?(dir) | |
notify "Entry already exists: #{dir}" | |
else | |
Dir.mkdir(dir) | |
File.open(File.join(dir, "value"), "w") do |f| | |
f.write("my secret password") | |
end | |
notify "New entry added: #{dir}" | |
end | |
end | |
end | |
#PUT /data/passwords/*/value | |
dirs.each do |path| | |
url = path[1..-1] | |
puts "Define: PUT #{url}" | |
put "#{url}" do | |
value = params["value"] | |
file = File.join(path, "value") | |
if File.exists?(file) | |
File.open(file, "w") do |f| | |
f.write(value) | |
notify "Entry updated: #{file}" | |
end | |
end | |
end | |
end | |
private | |
def notify(response) | |
response + "\n" | |
end | |
end | |
end | |
Sensive::DocServer.run! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment