Skip to content

Instantly share code, notes, and snippets.

@tmtm
Created November 26, 2010 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmtm/716878 to your computer and use it in GitHub Desktop.
Save tmtm/716878 to your computer and use it in GitHub Desktop.
Groonga HTTP Client for Ruby
require 'cgi'
require 'json'
require 'socket'
class GroongaHttpClient
Error = Class.new StandardError
def initialize(host, port)
@host, @port = host, port
end
[
:cache_limit,
:check,
:clearlock,
:column_create,
:column_list,
:column_remove,
:define_selector,
:defrag,
:delete,
:dump,
# :load,
:log_level,
:log_put,
:log_reopen,
:quit,
:select,
:shutdown,
:status,
:suggest,
:table_create,
:table_list,
:table_remove,
:view_add,
].each do |cmd|
define_method cmd do |*args|
command cmd, *args
end
end
def load(arg)
arg = arg.dup
if arg.key? :values
vkey = :values
elsif arg.key? "values"
vkey = "values"
end
arg[vkey] = arg[vkey].to_json
command "load", arg
end
private
def command(cmd, arg=nil)
uri = "/d/#{cmd}"
if arg
q = arg.map{|k,v| "#{k.to_s}=#{CGI.escape v.to_s}"}.join('&')
uri.concat "?#{q}"
end
sock = TCPSocket.new @host, @port
sock.puts "GET #{uri} HTTP/1.0\r\n\r\n"
res = sock.read
header, body = res.split(/^\r\n/, 2)
info, ret = JSON.parse(body)
errno, timestamp, elapsed, msg = info
raise Error, msg if errno != 0
return ret
end
end
@tmtm
Copy link
Author

tmtm commented Nov 27, 2010

Usage:
g = GroongaHttpClient.new(hostname, port)
g.load :table=>"tblname", :values=>[{"col1"=>"val1", "col2"=>"val2"}]
g.select :table=>"tblname", :query=>"col2:val2", :output_columns=>"col1"

@tmtm
Copy link
Author

tmtm commented Dec 20, 2010

I don't use open-uri because open-uri may be failed for long URI.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment