Tcl Library Source Code

Documentation
Login


[ Main Table Of Contents | Table Of Contents | Keyword Index | Categories | Modules | Applications ]

NAME

httpd - A TclOO and coroutine based web server

Table Of Contents

SYNOPSIS

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

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
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

This module implements a web server, suitable for embedding in an application. The server is object oriented, and contains all of the fundamentals needed for a full service website.

Minimal Example

Starting a web service requires starting a class of type httpd::server, and providing that server with one or more URIs to service, and httpd::reply derived classes to generate them.

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. Files that end in a .tml will be 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]

A complete example of an httpd server is in the /examples directory of Tcllib. It also show how to dispatch URIs to other processes via SCGI and HTTP proxies.

cd ~/tcl/sandbox/tcllib
tclsh examples/httpd.tcl

Classes

Class httpd::mime

A metaclass for MIME handling behavior across a live socket

Methods

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:

  1. Invokes the reset method for the object to populate default headers.

  2. Invokes the HttpHeaders method to stream the MIME headers out of the socket

  3. Invokes the request parse method to convert the stream of MIME headers into a dict that can be read via the request method.

  4. Stores the raw stream of MIME headers in the rawrequest variable of the object.

  5. Invokes the content method for the object, generating an call to the error method if an exception is raised.

  6. Invokes the output method 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

Delegate

Methods

Class httpd::server

ancestors: httpd::mime

Variable

Methods

Class httpd::server::dispatch

ancestors: httpd::server

Provide a backward compadible alias

Class httpd::content.redirect

Methods

Class httpd::content.cache

Methods

Class httpd::content.template

Methods

Class httpd::content.file

Class to deliver Static content When utilized, this class is fed a local filename by the dispatcher

Methods

Class httpd::content.exec

Variable

Methods

Class httpd::content.proxy

ancestors: httpd::content.exec

Return data from an proxy process

Methods

Class httpd::content.cgi

ancestors: httpd::content.proxy

Methods

Class httpd::protocol.scgi

Return data from an SCGI process

Methods

Class httpd::content.scgi

ancestors: httpd::content.proxy

Methods

Class httpd::server.scgi

ancestors: httpd::server

Act as an SCGI Server

Methods

Class httpd::content.websocket

Upgrade 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

Class httpd::reply.memchan

ancestors: httpd::reply

Methods

Class httpd::plugin.local_memchan

Methods

AUTHORS

Sean Woods

Bugs, Ideas, Feedback

This document, and the package it describes, will undoubtedly contain bugs and other problems. Please report such in the category network of the Tcllib Trackers. 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

Copyright © 2018 Sean Woods