Strotmann.de
25 Dec 2017

Gophermoon 0.2 - a Gopher-Server in Lua – Part 3

Gophermoon on Github

the sourcecode is now on Github @ https://github.com/cstrotm/gophermoon

With every blog post, I will post the link to the commit associated with the blog post.

Serving static text files

Today Gophermoon learned how to serve static text files. The program first looks at the selector send by the client. If the selector is empty, and uses the root directory.

--- read the selector from the client
selector = io.read()

--- remove CR (13/$0D) from input
selector=selector:sub(1, -2)

--- if an empty selector has been send, use the root
if selector == '' then
   selector = "/"
end

--- make selector relative to the gopher root
filepath = gopherroot .. selector

Next, if the selector points to a directory, it looks if there is a file names gophermap in the direcory. A gophermap file is a Gopher-Document describing the resources available in this directory (as well as links outside the directory). Gophermoon uses the same gophermap format as Gophernicus (see https://github.com/prologic/gophernicus/blob/master/README.Gophermap)

Welcome to GopherMoon @ defaultroutes.de
----------------------------------------
0Gophermoon 0.1 - a Gopher-Server in Lua -- Part 1      /gophermoon01.txt       blog.defaultroutes.de   70
0Gophermoon 0.1 - a Gopher-Server in Lua -- Part 2      /gophermoon02.txt       blog.defaultroutes.de   70
0Gophermoon 0.2 - a Gopher-Server in Lua -- Part 3      /gophermoon03.txt       blog.defaultroutes.de   70
0Gophermoon Sourcecode  /gophermoon     blog.defaultroutes.de   70

Lines that do not contain a tabulator are formatted as "i" (Information) file type.

--- if the selector points to a directory,
--- do we have a "gophermap" file? If "yes",
--- send that file. Else, if the selector
--- points to a (text-) file, send it
--- if both are false, send an error message
if isDir(filepath) then
   gophermap = filepath .. "/gophermap"
   if isReadable(gophermap) then
      send_gophermap(gophermap)
   end
else
   if isReadable(filepath) then
      send_textfile(filepath)
   else
      send_info("Welcome to GopherMoon @ defaultroutes.de")
      send_info("----------------------------------------")
      send_info("Error: Selector not found")
      send_end()
   end
end

If the selector isn't a directory, the program checks the selector is a readable file, and if it is, it sends the file gopher-style (with CR/LF and terminating the file with ".").

--- send a Textfile Gopher-style
function send_textfile(filepath)
   local f=io.open(filepath,"r")
   if f~=nil then
      for line in io.lines(filepath) do
	 io.write(line .. "\r\n")
      end
      io.close(f)
   end
   send_end()
end

The commit from today is https://github.com/cstrotm/gophermoon/commit/f300e28677059c9364151a89b36afe552d858700

Other posts
Creative Commons License
strotmann.de by Carsten Strotmann is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License .