Created
February 7, 2025 10:13
-
-
Save digininja/a98b3567e0aeb218d37cdd337bb12f34 to your computer and use it in GitHub Desktop.
An sample ICAP server written in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'socket' | |
class ICAPServer | |
def initialize(port = 1344) | |
@server = TCPServer.new(port) | |
puts "ICAP server started on port #{port}" | |
end | |
def run | |
loop do | |
client = @server.accept | |
handle_request(client) | |
client.close | |
end | |
end | |
private | |
def handle_request(client) | |
request = client.gets | |
puts "Received request: #{request.strip}" | |
if request.start_with?('OPTIONS') | |
handle_options(client) | |
elsif request.start_with?('REQMOD') | |
handle_reqmod(client) | |
else | |
client.puts "ICAP/1.0 400 Bad Request\r\n\r\n" | |
end | |
end | |
def handle_options(client) | |
response = <<~OPTIONS | |
ICAP/1.0 200 OK | |
Methods: REQMOD RESPMOD | |
Service: Ruby ICAP Server | |
Preview: 0 | |
Transfer-Preview: * | |
Allow: 204 | |
ISTag: "RubyICAPServer" | |
OPTIONS | |
client.puts response | |
puts "Responded to OPTIONS request" | |
end | |
def handle_reqmod(client) | |
headers = [] | |
while (line = client.gets.strip) != "" | |
headers << line | |
end | |
# Log and modify the request (example header addition) | |
puts "Original Headers:\n#{headers.join("\n")}" | |
headers << "X-Modified-By: Ruby ICAP Server" | |
# Send the modified response back | |
response = <<~REQMOD | |
ICAP/1.0 200 OK | |
Encapsulated: req-hdr=0, null-body=#{headers.join.length} | |
#{headers.join("\r\n")}\r\n | |
REQMOD | |
client.puts response | |
puts "Modified request sent back" | |
end | |
end | |
server = ICAPServer.new | |
server.run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment