github.com/micro/go-micro/examples@v0.0.0-20210105173217-bf4ab679e18b/greeter/srv/ruby/README.md (about)

     1  # Ruby Greeter Server
     2  
     3  This is an example of how to run a ruby service within the Micro world.
     4  
     5  ## Simple RPC
     6  
     7  examples/greeter/server/ruby/rpc_server.rb runs on localhost:8080 and responds to JSON RPC requests
     8  examples/greeter/client/ruby/rpc_client.rb demonstrates a client request to this service
     9  
    10  rpc_server.rb
    11  ```ruby
    12  server = WEBrick::HTTPServer.new :Port => 8080
    13  
    14  server.mount_proc '/' do |req, res|
    15    request = JsonRpcObjects::Request::parse(req.body)
    16    response = request.class::version.response::create({:msg => "hello " + request.params[0]["name"]})
    17    res.body = response.to_json
    18  end
    19  
    20  trap 'INT' do server.shutdown end
    21  
    22  server.start
    23  ```
    24  
    25  rpc_client.rb
    26  ```ruby
    27  uri = URI("http://localhost:8080")
    28  method = "Say.Hello"
    29  request = {:name => "John"}
    30  
    31  # create request
    32  req = JsonRpcObjects::Request::create(method, [request], :id => 1)
    33  
    34  # do request
    35  http = Net::HTTP.new(uri.host, uri.port)
    36  request = Net::HTTP::Post.new(uri.request_uri)
    37  request.content_type = 'application/json'
    38  request.body = req.to_json
    39  
    40  # parse response
    41  puts JsonRpcObjects::Response::parse(http.request(request).body).result["msg"]
    42  ```
    43  
    44  ## Sidecar Registration
    45  
    46  By registering with discovery using the sidecar, other services can find and query your service.
    47  
    48  An example server can be found at examples/greeter/server/ruby/sidecar_server.rb
    49  An example client can be found at examples/greeter/client/ruby/sidecar_client.rb 
    50  
    51  ### Run the proxy
    52  ```shell
    53  $ go get github.com/micro/micro
    54  $ micro proxy
    55  ```
    56  
    57  ### Register
    58  ```ruby
    59  # service definition
    60  service = {
    61    "name" => service,
    62    "nodes" => [{
    63      "id" => service + "-" + SecureRandom.uuid,
    64      "address" => host,
    65      "port" => port
    66    }]
    67  }
    68  
    69  # registration url
    70  register_uri = URI("http://localhost:8081/registry")
    71  
    72  # register service
    73  http = Net::HTTP.new(register_uri.host, register_uri.port)
    74  request = Net::HTTP::Post.new(register_uri.request_uri)
    75  request.content_type = 'application/json'
    76  request.body = service.to_json
    77  http.request(request)
    78  
    79  # degister service
    80  request = Net::HTTP::Delete.new(register_uri.request_uri)
    81  request.content_type = 'application/json'
    82  request.body = service.to_json
    83  http.request(request)
    84  ```