Class: PicklesHttpServer::Server

Inherits:
Object
  • Object
show all
Includes:
Utils
Defined in:
lib/pickles_http/server.rb

Constant Summary

Constants included from RequestMethods

RequestMethods::DELETE, RequestMethods::GET, RequestMethods::OPTIONS, RequestMethods::POST, RequestMethods::PUT

Constants included from LogMode

LogMode::DEBUG, LogMode::ERROR, LogMode::FATAL, LogMode::INFO, LogMode::SEVERITIES, LogMode::WARN

Constants included from ContentTypes

ContentTypes::HTML, ContentTypes::JSON, ContentTypes::MJS, ContentTypes::MP3

Constants included from HttpStatusCodes

HttpStatusCodes::BAD_REQUEST, HttpStatusCodes::INTERNAL_SERVER_ERROR, HttpStatusCodes::NOT_FOUND, HttpStatusCodes::OK

Instance Method Summary collapse

Methods included from Utils

parse_request

Constructor Details

#initialize(port, log_file, host) ⇒ Server

Returns a new instance of Server.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/pickles_http/server.rb', line 15

def initialize(port, log_file, host)
  @port = port
  @socket = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM)

  addr = Socket.pack_sockaddr_in(port, '127.0.0.1')
  @socket.bind(addr)
  @socket.listen(Socket::SOMAXCONN)
  @socket.setsockopt(:SOCKET, :REUSEADDR, true)

  @router = Router.new
  @logger = PicklesHttpServer::Logger.new(log_file)
  @request_queue = SizedQueue.new(10)
  @write_mutex = Mutex.new
  @middlewares = []
  @not_found_message = "404: Route not found"
end

Instance Method Details

#add_route(method, path, handler) ⇒ Object



36
37
38
# File 'lib/pickles_http/server.rb', line 36

def add_route(method, path, handler)
  @router.add_route(method, path, handler)
end

#change_server_option(option, value) ⇒ Object



32
33
34
# File 'lib/pickles_http/server.rb', line 32

def change_server_option(option, value)
  @not_found_message = value if option == "set_default_not_found_message"
end

#startObject



44
45
46
47
48
# File 'lib/pickles_http/server.rb', line 44

def start
  puts "PicklesServer is running on http://localhost:#{@port} 🔥"
  start_request_processing_thread
  accept_and_process_requests
end

#use_middleware(middleware) ⇒ Object



40
41
42
# File 'lib/pickles_http/server.rb', line 40

def use_middleware(middleware)
  @middlewares << middleware
end