环境准备:
# gem install em-synchrony
# gem install mysql2
创建数据库:
# create database goliath_test
# create user 'goliath'@'localhost' identified by 'goliath'
# grant all on goliath_test.* to 'goliath'@'localhost'
# create table users (id int not null auto_increment primary key, name varchar(255), email varchar(255));
# insert into users (name, email) values ('dan', '[email protected]'), ('Ilya', '[email protected]');
/srv.rb
require 'goliath' require 'em-synchrony/activerecord' require 'yajl' if RUBY_PLATFORM != 'java' class User < ActiveRecord::Base end class Srv < Goliath::API use Goliath::Rack::Params use Goliath::Rack::DefaultMimeType use Goliath::Rack::Render, 'json' use Goliath::Rack::Validation::RequiredParam, {:key => 'id', :type => 'ID'} use Goliath::Rack::Validation::NumericRange, {:key => 'id', :min => 1} def response(env) [200, {}, User.find(params['id']).to_json] end end
同级目录中新建文件config/srv.rb
require 'mysql2' ActiveRecord::Base.establish_connection(:adapter => 'em_mysql2', :database => 'goliath_test', :username => 'goliath', :password => 'goliath', :host => 'localhost', :pool => 5)
测试:
# To start server
# ruby srv.rb -sv
# Example output:
# curl http://localhost:9000/?id=1
#=> "{\"user\":{\"email\":\"[email protected]\",\"id\":1,\"name\":\"dan\"}}"
# curl http://localhost:9000/?id=2
#=> "{\"user\":{\"email\":\"[email protected]\",\"id\":2,\"name\":\"Ilya\"}}"
文件结构:
.
├── config
│ ├── apiserver.rb
│ └── srv.rb
├── server.rb
├── srv.rb
└── test.rb
注意Srv的类名转化成小写要与config/srb.rb 的文件名相同,否则goliath找不到配置文件
class Srv < Goliath::API