basic web server in Genie language
def default_handler (server:Soup.Server, msg:Soup.ServerMessage, path:string, query:GLib.HashTable?)
print @"path: $path"
response_text:string=""
content_type:string=""
status_code:int=0
status_txt:string=""
// if path starts with a "."
if path.has_prefix(".")
//return 404
print "starts with ."
response_text = "invalid request"
content_type = "text/plain"
status_code=400
status_txt="Bad Request"
else
// redirect / to index
if path == "/"
path = "/index.html"
// modify path to start looking in current dir
var curpath = "."+path
/* is the path a file in the current dir? */
f:File = File.new_for_path(curpath)
type:FileType = f.query_file_type (FileQueryInfoFlags.NONE)
// does the file exist?
if f.query_exists() and type==FileType.REGULAR
// is file and not directory?
// get the ext
var fileparts = path.split(".")
var ext = fileparts[fileparts.length-1].down()
content_type = "text/plain"
status_code = 200
status_txt = "OK"
case ext
when "html"
content_type = "text/html"
when "css"
content_type = "text/css"
when "js"
content_type = "text/javascript"
// read the file
contents:string
FileUtils.get_contents(curpath, out response_text)
else
print "not found"
print path
response_text = @"Not Found: $path"
status_code = 404
status_txt = "Not Found"
content_type = "text/plain"
msg.set_status(status_code, status_txt)
msg.set_response (content_type, Soup.MemoryUse.COPY, response_text.data)
// do not cache
msg.get_response_headers().append("Cache-Control","no-cache")
// start the app
init
port:int = 8080
var server = new Soup.Server("server-header", "genie server 0.1")
try
server.listen_all(port, Soup.ServerListenOptions.IPV4_ONLY )
print "serving on port: %d".printf(port)
server.add_handler ("/", default_handler)
loop:MainLoop = new MainLoop()
loop.run()
except
print "can not bind to port %d".printf(port)