goliath 连接mysql

 

环境准备:

# 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
2. 使用Grape
require 'goliath'
require 'em-synchrony/activerecord'
require 'yajl' if RUBY_PLATFORM != 'java'
require 'grape'

class User < ActiveRecord::Base
end

class MyAPI < Grape::API

  version 'v1', :using => :path
  format :json

  resource 'users' do
    get "/" do
      User.all
    end

    get "/:id" do
      User.find(params['id'])
    end

    post "/create" do
      User.create(params['user'])
    end
  end

end

class APIServer < Goliath::API

  def response(env)
    MyAPI.call(env)
  end

end
 
测试:
# 4. Try Examples
# curl http://localhost:9000/v1/users/2.json
# => {"email":"[email protected]","id":2,"name":"Ilya"}

# All users
# curl http://localhost:9000/v1/users

# Create a new user
# curl -X POST -d '{"user":{"name":"David Jones","email":"[email protected]"}}' http://localhost:9000/v1/users/create
 

更多精彩内容:

你可能感兴趣的:(mysql,goliath)