httpd(n)
π httpd(n) β the Tcl Web Server, bestie edition π
okay so. say hi to httpd, from the Tcl Web Server manual. this is part 1 of 3, so buckle up buttercup π
β¨ SYNOPSIS β¨
first you gotta pull in the whole friend group, fr fr:
package require Tcl 8.6 9
package require uuid
package require clay
package require coroutine
package require fileutil
package require fileutil::magic::filetype
package require websocket
package require mime
package require cron
package require uri
package require Markdown
and here's the full roster of methods and variables, no cap, every single one:
method ChannelCopy in out ?args?
method html_header ?title ? ?args?
method html_footer ?args?
method http_code_string code
method HttpHeaders sock ?debug ?
method HttpHeaders_Default
method HttpServerHeaders
method MimeParse mimetext
method Url_Decode data
method Url_PathCheck urlsuffix
method wait mode sock
variable ChannelRegister
variable reply
variable request
delegate <server>
method constructor ServerObj ?args?
method destructor ?dictargs?
method ChannelRegister ?args?
method close
method Log_Dispatched
method dispatch newsock datastate
method Dispatch
method html_header title ?args?
method html_footer ?args?
method error code ?msg ? ?errorInfo ?
method content
method EncodeStatus status
method log type ?info ?
method CoroName
method DoOutput
method FormData
method PostData length
method Session_Load
method puts line
method RequestFind field
method request subcommand ?args?
method reply subcommand ?args?
method reset
method timeOutCheck
method timestamp
variable template
variable url_patterns
method constructor args ?port auto? ?myaddr 127.0.0.1? ?string auto? ?name auto? ?doc_root ? ?reverse_dns 0? ?configuration_file ? ?protocol HTTP/1.1?
method destructor ?dictargs?
method connect sock ip port
method ServerHeaders ip http_request mimetxt
method Connect uuid sock ip
method counter which
method CheckTimeout
method debug ?args?
method dispatch data
method Dispatch_Default reply
method Dispatch_Local data
method Headers_Local varname
method Headers_Process varname
method HostName ipaddr
method log ?args?
method plugin slot ?class ?
method port_listening
method PrefixNormalize prefix
method source filename
method start
method stop
method SubObject {} db
method SubObject {} default
method template page
method TemplateSearch page
method Thread_start
method Uuid_Generate
method Validate_Connection sock ip
method reset
method content
method Dispatch
method content
method FileName
method DirectoryListing local_file
method content
method Dispatch
variable exename
method CgiExec execname script arglist
method Cgi_Executable script
method proxy_channel
method proxy_path
method ProxyRequest chana chanb
method ProxyReply chana chanb ?args?
method Dispatch
method FileName
method proxy_channel
method ProxyRequest chana chanb
method ProxyReply chana chanb ?args?
method DirectoryListing local_file
method EncodeStatus status
method scgi_info
method proxy_channel
method ProxyRequest chana chanb
method ProxyReply chana chanb ?args?
method debug ?args?
method Connect uuid sock ip
method Dispatch_Dict data
method uri {} add vhosts patterns info
method uri {} direct vhosts patterns info body
method output
method DoOutput
method close
method local_memchan command ?args?
method Connect_Local uuid sock ?args?
πΈ DESCRIPTION πΈ
okay so this module is a whole web server, and the whole point is that you can embed it inside your app π«Ά. it's object oriented, and it's got literally all the fundamentals you need for a full service website. it's giving "I contain multitudes" energy π
π¦ MINIMAL EXAMPLE π¦
to spin up a web service you gotta create a class of type httpd::server, hand that server one or more URIs to service, and give it httpd::reply derived classes to actually generate those URIs. the vibes:
oo::class create ::reply.hello {
method content {} {
my puts "<HTML><HEAD><TITLE>IRM Dispatch Server</TITLE></HEAD><BODY>"
my puts "<h1>Hello World!</h1>"
my puts </BODY></HTML>
}
}
::httpd::server create HTTPD port 8015 myaddr 127.0.0.1 doc_root ~/htdocs
HTTPD plugin dispatch httpd::server::dispatch
HTTPD uri add * /hello [list mixin reply.hello]
the bare module does have facilities to hose a files from a file system, bestie. files that end in a .tml get substituted in the style of Tclhttpd:
<!-- hello.tml -->
[my html_header {Hello World!}]
Your Server is running.
<p>
The time is now [clock format [clock seconds]]
[my html_footer]
there's a complete example of an httpd server in the /examples directory of Tcllib π. it also shows how to dispatch URIs to other processes via SCGI and HTTP proxies, which is lowkey iconic:
cd ~/tcl/sandbox/tcllib
tclsh examples/httpd.tcl
π CLASSES π
π CLASS HTTPD::MIME
a metaclass for MIME handling behavior across a live socket β¨
Methods
method ChannelCopy in out ?args?method html_header ?title ? ?args?β returns a block of HTML πmethod html_footer ?args?method http_code_string codemethod HttpHeaders sock ?debug ?method HttpHeaders_Defaultmethod HttpServerHeadersmethod MimeParse mimetextβ converts a block of mime encoded text to a key/value list. but listen: if an exception gets encountered, the method generates its own call to theerrormethod, and immediately invokes theoutputmethod to produce an error code and close the connection. so it handles its own drama πmethod Url_Decode dataβ de-httpizes a string π§method Url_PathCheck urlsuffixmethod wait mode sock
π CLASS HTTPD::REPLY
ancestors: httpd::mime
a class which shephards a request through the process of generating a reply π«Ά. the socket associated with the reply is available at all times as the chan variable. the process of generating a reply begins with an httpd::server generating a http::class object, mixing in a set of behaviors and then invoking the reply object's dispatch method. in normal operations the dispatch method does this, in order:
- invokes the
resetmethod for the object to populate default headers β¨ - invokes the
HttpHeadersmethod to stream the MIME headers out of the socket π - invokes the
requestparse method to convert the stream of MIME headers into a dict that can be read via therequestmethod π - stores the raw stream of MIME headers in the
rawrequestvariable of the object ποΈ - invokes the
contentmethod for the object, generating an call to theerrormethod if an exception is raised π - invokes the
outputmethod for the object π
developers have the option of streaming output to a buffer via the puts method of the reply, or simply populating the reply_body variable of the object. the information returned by the content method is not interpreted in any way π. if an exception is thrown (via the error command in Tcl, for example) the caller will auto-generate a 500 {Internal Error} message π. a typical implementation of content look like:
clay::define ::test::content.file {
superclass ::httpd::content.file
# Return a file
# Note: this is using the content.file mixin which looks for the reply_file variable
# and will auto-compute the Content-Type
method content {} {
my reset
set doc_root [my request get DOCUMENT_ROOT]
my variable reply_file
set reply_file [file join $doc_root index.html]
}
}
clay::define ::test::content.time {
# return the current system time
method content {} {
my variable reply_body
my reply set Content-Type text/plain
set reply_body [clock seconds]
}
}
clay::define ::test::content.echo {
method content {} {
my variable reply_body
my reply set Content-Type [my request get CONTENT_TYPE]
set reply_body [my PostData [my request get CONTENT_LENGTH]]
}
}
clay::define ::test::content.form_handler {
method content {} {
set form [my FormData]
my reply set Content-Type {text/html; charset=UTF-8}
my puts [my html_header {My Dynamic Page}]
my puts "<BODY>"
my puts "You Sent<p>"
my puts "<TABLE>"
foreach {f v} $form {
my puts "<TR><TH>$f</TH><TD><verbatim>$v</verbatim></TD>"
}
my puts "</TABLE><p>"
my puts "Send some info:<p>"
my puts "<FORM action=/[my request get REQUEST_PATH] method POST>"
my puts "<TABLE>"
foreach field {name rank serial_number} {
set line "<TR><TH>$field</TH><TD><input name=\"$field\" "
if {[dict exists $form $field]} {
append line " value=\"[dict get $form $field]\"""
}
append line " /></TD></TR>"
my puts $line
}
my puts "</TABLE>"
my puts [my html footer]
}
}
Variable
variable ChannelRegistervariable replyβ a dictionary which will converted into the MIME headers of the reply πvariable requestβ a dictionary containing the SCGI transformed HTTP headers for the request π¬
Delegate
delegate <server>β the server object which spawned this reply π
Methods
method constructor ServerObj ?args?method destructor ?dictargs?β clean up on exit π§Ήmethod ChannelRegister ?args?β registers a channel to be closed by theclosemethodmethod closeβ close channels opened by this object πͺmethod Log_Dispatchedβ record a dispatch event πmethod dispatch newsock datastateβ accept the handoff from the server object of the socketnewsockand feed it the statedatastate. fields thedatastateare looking for in particular are:mixinβ a key/value list of slots and classes to be mixed into the object prior to invokingDispatch.
(part 2 is coming bestie, don't go anywhere π)
httpβ a key/value list of values that populates the object's request ensemble β¨
All the other fields get passed along to the clay structure of the object. that's the whole note π
method Dispatchβ the source gives us literally zero description here, so... mystery πmethod html_header title ?args?β no notes in the original, bestie πmethod html_footer ?args?β also undescribed, we move π¦method error code ?msg ? ?errorInfo ?β no description given πmethod contentβ REPLACE ME: this method is the "meat" of your application π₯ It writes to the result buffer via theputsmethod, and it can tweak the headers viaclay put header_reply.method EncodeStatus statusβ formulates a standard HTTP status header from the string provided πmethod log type ?info ?β no description in the source, iykykmethod CoroNameβ undescribed π¦method DoOutputβ generates the HTTP reply, streams that reply back acrosschan, and destroys the object π₯method FormDataβ okay so for GET requests this converts theQUERY_DATAheader into a key/value list. For POST requests, it reads the Post data and converts that info into a key/value list forapplication/x-www-form-urlencodedposts. For multipart posts, it composites all of the MIME headers of the post into a singular key/value list, and providesMIME_*information as computed by themimepackage β including theMIME_TOKEN, which can be fed right back into themimepackage to read out the contents πmethod PostData lengthβ streamslengthbytes from thechansocket, but only if the request is a POST or PUSH. Returns an empty string otherwise β¨method Session_Loadβ manages session data πΈmethod puts lineβ appends the value of string to the end ofreply_body, plus a trailing newline character π«Άmethod RequestFind fieldβ no description given πmethod request subcommand ?args?β undescribed, moving on β¨method reply subcommand ?args?β same, no notes πmethod resetβ clears the contents of thereply_bodyvariable, and resets all the headers in the reply structure back to the defaults for this object π§method timeOutCheckβ called from thehttp::serverobject that spawned this reply. It checks whether too much time has elapsed while waiting for data or generating a reply, and if it has, it issues a timeout error to the request, destroys the object, and closes thechansocket πmethod timestampβ returns the current system time in this format:
%a, %d %b %Y %T %Z
π CLASS HTTPD::SERVER π
ancestors: httpd::mime
π Variable
variable templatevariable url_patterns
β¨ Methods β¨
method constructor args ?port auto? ?myaddr 127.0.0.1? ?string auto? ?name auto? ?doc_root ? ?reverse_dns 0? ?configuration_file ? ?protocol HTTP/1.1?β no description in the source, but look at all those defaults, bestie πmethod destructor ?dictargs?β undescribed πmethod connect sock ip portβ replies to an open socket. This method builds a coroutine to manage the rest of the connection, and that coroutine's operations are driven by theConnectmethod π¦method ServerHeaders ip http_request mimetxtβ no description given πmethod Connect uuid sock ipβ this one reads the HTTP headers, then consults thedispatchmethod to figure out whether the request is valid and/or what kind of reply to generate. In the normal case, an object of class::http::replygets created, and that class'sdispatchmethod runs. This hands control of the socket over to the reply object, and the reply object manages the rest of the transaction β including closing the socket πmethod counter whichβ increments an internal counter β¨method CheckTimeoutβ checks open connections for a time out event πmethod debug ?args?β undescribed πmethod dispatch dataβ given a key/value list of information, returns a data structure describing how the server should reply πmethod Dispatch_Default replyβ thedispatchmethod of last resort, before returning a 404 NOT FOUND error. The default behavior is to look for a file inDOCUMENT_ROOTthat matches the query π₯method Dispatch_Local dataβ thedispatchmethod invoked before any methods implemented by plugins run. If this method returns a non-empty dictionary, that structure gets passed to the reply. The default is an empty implementation πΈmethod Headers_Local varnameβ introspects and possibly modifies a data structure destined for a reply. Invoked before the Header methods implemented by plugins run. The default implementation is empty π¦method Headers_Process varnameβ introspects and possibly modifies a data structure destined for a reply. This method is built dynamically by thepluginmethod β¨method HostName ipaddrβ converts an ip address into a host name. If the server'sreverse_dnsflag is false, this method just hands the IP address right back. Internally it uses thednsmodule from tcllib πmethod log ?args?β logs an event. The input forargsis free form. This method is intended to be replaced by the user, and it's anoopfor a stockhttp::serverobject πmethod plugin slot ?class ?β incorporates behaviors from a plugin. This method dynamically rebuilds theDispatchandHeadersmethods. For every plugin, the server looks for these entries inclay plugin/:loadβ a script to invoke in the server's namespace during thepluginmethod invocation.dispatchβ a script to stitch into the server'sDispatchmethod.headersβ a script to stitch into the server'sHeadersmethod.threadβ a script to stitch into the server'sThread_startmethod.
method port_listeningβ returns the actual port that httpd is listening on πmethod PrefixNormalize prefixβ for the stock version, trims trailing/'s and*'s from a prefix. The end user can replace this method to perform any other transformations their application needs π§method source filenameβ undescribed πmethod startβ opens the socket listener π₯method stopβ shuts off the socket listener, and destroys any pending replies πmethod SubObject {} dbβ no description given πmethod SubObject {} defaultβ also undescribed π¦method template pageβ returns a template for the stringpageβ¨method TemplateSearch pageβ searches for the template that best matchespage. This can include local file searches, in-memory structures, or even database lookups. The stock implementation simply looks for files with a.tmlor.htmlextension in the?doc_root?directory πΈmethod Thread_startβ built by thepluginmethod. Called by thestartmethod. Intended to let plugins spawn worker threads πmethod Uuid_Generateβ generates a GUUID. Used to make sure every request has a unique ID. The default implementation is:
return [::clay::uuid generate]
method Validate_Connection sock ipβ given a socket and an ip address, returns true if this connection should be terminated, or false if it should be allowed to continue. The stock implementation always returns0. This is intended so applications can implement black lists and/or provide security based on IP address π
π CLASS HTTPD::SERVER::DISPATCH π
ancestors: httpd::server
Provides a backward compatible alias β¨
π CLASS HTTPD::CONTENT.REDIRECT π
β¨ Methods β¨
method resetmethod content
π CLASS HTTPD::CONTENT.CACHE π
β¨ Methods β¨
method Dispatch
π CLASS HTTPD::CONTENT.TEMPLATE π
β¨ Methods β¨
method content
π CLASS HTTPD::CONTENT.FILE π
A class to deliver static content. When it's utilized, this class gets fed a local filename by the dispatcher π
β¨ Methods β¨
method FileNamemethod DirectoryListing local_filemethod contentmethod Dispatch
π CLASS HTTPD::CONTENT.EXEC π
π Variable
variable exename
β¨ Methods β¨
method CgiExec execname script arglistmethod Cgi_Executable script
π CLASS HTTPD::CONTENT.PROXY π
ancestors: httpd::content.exec
Returns data from a proxy process π¦
β¨ Methods β¨
method proxy_channelmethod proxy_pathmethod ProxyRequest chana chanbmethod ProxyReply chana chanb ?args?method Dispatch
π CLASS HTTPD::CONTENT.CGI π
ancestors: httpd::content.proxy
β¨ Methods β¨
method FileNamemethod proxy_channelmethod ProxyRequest chana chanbmethod ProxyReply chana chanb ?args?method DirectoryListing local_fileβ for most CGI applications a directory list is vorboten π
π CLASS HTTPD::PROTOCOL.SCGI π
Returns data from an SCGI process π
β¨ Methods β¨
method EncodeStatus status
π CLASS HTTPD::CONTENT.SCGI π
ancestors: httpd::content.proxy
β¨ Methods β¨
method scgi_infomethod proxy_channelmethod ProxyRequest chana chanbmethod ProxyReply chana chanb ?args?
π CLASS HTTPD::SERVER.SCGI π
ancestors: httpd::server
Acts as an SCGI Server π
β¨ Methods β¨
method debug ?args?method Connect uuid sock ip
π CLASS HTTPD::CONTENT.WEBSOCKET π
Upgrades a connection to a websocket π
π CLASS HTTPD::PLUGIN π
httpd plugin template π
π CLASS HTTPD::PLUGIN.DICT_DISPATCH π
A rudimentary plugin that dispatches URLs from a dict data structure π
β¨ Methods β¨
method Dispatch_Dict dataβ implementation of the dispatcher πmethod uri {} add vhosts patterns infomethod uri {} direct vhosts patterns info body
π CLASS HTTPD::REPLY.MEMCHAN π
ancestors: httpd::reply
β¨ Methods β¨
method outputmethod DoOutputmethod close
π CLASS HTTPD::PLUGIN.LOCAL_MEMCHAN π
β¨ Methods β¨
method local_memchan command ?args?method Connect_Local uuid sock ?args?β a modified connection method that passes simple GET requests to an object and pulls data directly from thereply_bodydata variable in the object. Needed because memchan is bidirectional, and we can't seem to communicate that the server is one side of the link and the reply is another π
π AUTHORS π
Sean Woods
π BUGS, IDEAS, FEEDBACK π
This document, and the package it describes, will undoubtedly contain bugs and other problems. bestie, please report such in the category network of the Tcllib Trackers http://core.tcl.tk/tcllib/reportlist π«Ά Please also report any ideas for enhancements you may have for either package and/or documentation.
When proposing code changes, please provide unified diffs, i.e. the output of diff -u.
Note further that attachments are strongly preferred over inlined patches. Attachments can be made by going to the Edit form of the ticket immediately after its creation, and then using the left-most button in the secondary navigation bar π
β¨ KEYWORDS β¨
TclOO, WWW, http, httpd, httpserver, services
π CATEGORY π
Networking
π COPYRIGHT π
Okay bestie, legal era, we're almost done, stay with me π«Ά
Copyright Β© 2018 Sean Woods <yoda@etoyoc.com> β that's the icon who made this whole thing, show some respect π
β¨
And that's a wrap on the whole page, fr fr π β brought to you by tcllib, version 4.3.6, starring our main character httpd(n). Go forth and serve some pages, you absolute legend ππΈ
π¦ where this page comes from
- fedora 43: tcllib 2.0-3.fc43 Β· TCL
- fedora 44: tcllib 2.0-4.fc44 Β· TCL
- nixos 26.05: tcllib 2.0
- nixpkgs unstable: tcllib 2.0
- Copyright (c) 2018 Sean Woods <yoda@etoyoc\&.com>
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms