diff --git a/ruby-server-example/Dockerfile b/ruby-server-example/Dockerfile new file mode 100644 index 0000000..6fa7846 --- /dev/null +++ b/ruby-server-example/Dockerfile @@ -0,0 +1,15 @@ +# Ruby Alpine image (after using bsf dockerfile digest) +FROM ruby:3.1-alpine AS build +# Install all required dependencies for Ruby gems +RUN apk add --no-cache build-base libxml2-dev libxslt-dev tzdata +WORKDIR /src +# Copy the Gemfile and Gemfile.lock into the container +COPY Gemfile /src/ +# Install the required gems +RUN bundle install +# Copy the rest of the application files to the container +COPY . /src +# Expose the application port +EXPOSE 9898 +# Command to run the Ruby application +CMD ["ruby", "main.rb"] \ No newline at end of file diff --git a/ruby-server-example/Gemfile b/ruby-server-example/Gemfile new file mode 100644 index 0000000..b7f1257 --- /dev/null +++ b/ruby-server-example/Gemfile @@ -0,0 +1,3 @@ +source 'https://rubygems.org' + +gem 'activesupport', '~> 7.0' \ No newline at end of file diff --git a/ruby-server-example/main.rb b/ruby-server-example/main.rb new file mode 100644 index 0000000..49de1a0 --- /dev/null +++ b/ruby-server-example/main.rb @@ -0,0 +1,43 @@ +require "socket" +require "json" +require "active_support/all" + +port = ENV.fetch("PORT", 9898).to_i +server = TCPServer.new port +puts "Listening on port #{port}..." + +def handle_request(request) + method, path, _ = request.split(" ") + + case [method, path] + when ["GET", "/ping"] + { code: 200, body: "Pong!" } + else + { code: 404, body: "Not Found" } + end +end + +def send_response(client, response) + status_line = case response[:code] + when 200 then "HTTP/1.1 200 OK\r\n" + when 404 then "HTTP/1.1 404 Not Found\r\n" + when 400 then "HTTP/1.1 400 Bad Request\r\n" + else "HTTP/1.1 500 Internal Server Error\r\n" + end + + headers = response[:headers] || { "Content-Type" => "text/html" } + headers_section = headers.map { |k, v| "#{k}: #{v}" }.join("\r\n") + + client.write(status_line) + client.write(headers_section + "\r\n\r\n") + client.write(response[:body]) if response[:body] +end + +loop do + Thread.start(server.accept) do |client| + request = client.readpartial(2048) + response = handle_request(request) + send_response(client, response) + client.close + end +end \ No newline at end of file