Updated 2011-06-22 10:19:40 by RLE

Super-mini web server that I use as a demonstration for presentations. Not correct or complete, but it does serve files...

It can also reload its own code if you hit it at the /reload url!
 proc Serve {chan addr port} {
    fconfigure $chan -translation auto -buffering line
    set line [gets $chan]
    set path [file join . [string trimleft [lindex $line 1] /]]
    if { $path == "." } {set path ./index.html}
    if { $path == "./reload" } {
        set reload 1
        source [info script]
        puts $chan "HTTP/1.0 200 OK"
        puts $chan "Content-Type: text/html"
        puts $chan ""
        puts $chan "Server reloaded"
    } else {
       #puts "Request: $path"                ;##
        if { [catch {
            set fl [open $path]
        } err] } {
            puts $chan "HTTP/1.0 404 Not Found"
        } else {
            puts $chan "HTTP/1.0 200 OK"
            puts $chan "Content-Type: text/html"
            puts $chan ""
            puts $chan [read $fl]
            close $fl
        close $chan

 #catch {console show}                ;##
 if { ! [info exists reload] } {
    set sk [socket -server Serve 5151]
    vwait forever
 } else {
    unset reload

Point your browser to http://localhost:5151

HJG Added "index.html" as default-url.

slebetman Whoa! Smaller than the DustMote and has the extra feature of being able to re-source itself! Impressive.

escargo 30 Nov 2006 - Won't this break if the input line can't be indexed with lindex?

MG guesses that it may need to be
 set line [split [gets $chan] " "]

to make sure it's parsed properly as a list.

slebetman The HTTP spec forbids list-unfriendly characters {[}] in URIs and neither the command nor the HTTP version number in the first line contain list-unfriendly characters. So the first line of a HTTP request (the only thing this code is processing) should in theory be completely parsable as a list. If it breaks then it isn't a valid HTTP request and we should ignore it. A simple catch wrapping the lindex should do the trick.

escargo 1 Dec 2006 - I was putting my paranoid hat on, thinking about what happens with deliberately (or accidentally) unfriendly characters. A denial-of-service attack that's easy to guard against seems like a good idea.

AMG: That reloading functionality is pretty cool. Here's how to add it to Wibble: [1]

See also edit