webfw: github.com/urandom/webfw Index | Examples | Files | Directories

package webfw

import "github.com/urandom/webfw"

Copyright 2011 Viktor Kojouharov. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

Package webfw provides a set of tools for building web applications and services in go

Some of the provided features are:

    * Dispatchers that provide custom routing with support for path
	  parameters, and act as handlers for go's net/http server
    * Customizable middleware handlers and support for custom ones.
      Some of the included middleware provide:
        - Panic handling
        - GZipping response
        - Static files and directory listing
        - I18N via github.com/nicksnyder/go-i18n/i18n
        - Access logging
        - Context and sessions

    * Configuration via code.google.com/p/gcfg
    * Controllers registered for a particular pattern and method(s),
      which ultimately provide http.HandlerFunc funcions

    * A helper renderer utility that caches html/template chains and
      provides context data for the Dot

Since webfw uses sync.Pool internally, it currently requires go1.3 as its lowest supported version.


package main

import (


type Hello struct {

func NewHello(pattern string) Hello {
    return Hello{webfw.NewBasePatternController(pattern, webfw.MethodAll, "")}

func (con Hello) Handler(c context.Context) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        params := webfw.GetParams(c, r)
        d := renderer.RenderData{"name": params["name"]}

        err := webfw.GetRenderCtx(c, r)(w, d, "hello.tmpl")
        if err != nil {

func main() {
    s := webfw.NewServer()

    dispatcher := s.Dispatcher("/")

    if err := s.ListenAndServe(); err != nil {

func main() {



Package Files

config.go context_util.go controller.go dispatcher.go doc.go logger.go middleware.go request_util.go route.go server.go sitemap.go trie.go


const (
    SitemapFrequencyAlways  SitemapFrequency = "always"
    SitemapFrequencyHourly  SitemapFrequency = "hourly"
    SitemapFrequencyDaily   SitemapFrequency = "daily"
    SitemapFrequencyWeekly  SitemapFrequency = "weekly"
    SitemapFrequencyMonthly SitemapFrequency = "monthly"
    SitemapFrequencyYearly  SitemapFrequency = "yearly"
    SitemapFrequencyNever   SitemapFrequency = "never"

    SitemapNoFrequency SitemapFrequency = ""
    SitemapNoPriority  float64          = -1


var DefaultCfg string = "" /* 766 byte string literal not displayed */

Default configuration

var MethodNames map[Method]string = map[Method]string{
    MethodGet:    "GET",
    MethodPost:   "POST",
    MethodPut:    "PUT",
    MethodDelete: "DELETE",
    MethodPatch:  "PATCH",
    MethodHead:   "HEAD",
var ReverseMethodNames = map[string]Method{
    "GET":    MethodGet,
    "POST":   MethodPost,
    "PUT":    MethodPut,
    "DELETE": MethodDelete,
    "PATCH":  MethodPatch,
    "HEAD":   MethodHead,
var (
    SitemapNoLastMod = time.Unix(0, 0)

func GetFallbackLanguage Uses

func GetFallbackLanguage(c context.Context, r *http.Request, fallback ...string) string

GetFallbackLanguage tries to obtain a requested language via the session, or the Accept-Language request header, or the LANG or LC_MESSAGES environment variables

func GetForward Uses

func GetForward(c context.Context, r *http.Request) string

GetForwards returns a set forward path as a string, or the empty string.

func GetLanguage Uses

func GetLanguage(c context.Context, r *http.Request) string

GetLanguage returns the current request language, such as "en", or "bg-BG" from the context, if the I18N middleware is in use.

func GetMultiPatternIdentifier Uses

func GetMultiPatternIdentifier(c context.Context, r *http.Request) string

GetMultiPatternIdentifier returns the identifier for the current multi-pattern route.

func GetNamedForward Uses

func GetNamedForward(c context.Context, r *http.Request) string

GetNamedForward returns a name, used by the dispatcher to lookup a route to forward to.

func GetRenderCtx Uses

func GetRenderCtx(c context.Context, r *http.Request) renderer.RenderCtx

GetRenderCtx returns a RenderCtx wrapper around the current raw renderer The wrapper automatically adds the current request ContextData to the renderer's Render method call.

func GetRenderer Uses

func GetRenderer(c context.Context) renderer.Renderer

GetRenderer returns the current raw renderer from the context.

func GetSession Uses

func GetSession(c context.Context, r *http.Request) context.Session

GetSession returns the current session from the context, if the Session middleware is in use.

func RemoteAddr Uses

func RemoteAddr(r *http.Request) string

RemoteAddr returns the real IP address from the request, checking for X-Real-Ip and X-Forwarded-For headers.

type BasePatternController Uses

type BasePatternController struct {
    // contains filtered or unexported fields

func NewBasePatternController Uses

func NewBasePatternController(pattern string, method Method, name string) BasePatternController

New creates a base controller.

func (BasePatternController) Method Uses

func (b BasePatternController) Method() Method

Method returns the method(s) for the controller. Since the Method constants are bitmasks, a controller may handle more than one method at a time.

func (BasePatternController) Name Uses

func (b BasePatternController) Name() string

Name returns the name a controller may be referred to.

func (BasePatternController) Pattern Uses

func (b BasePatternController) Pattern() string

Pattern returns the pattern associated with the controller. It may contain named parameters and globs. For example:

- "/hello/:first/:last" will fill RouteParams with whatever the url
  contains in place of :first under the key "first", and likewise for
  "last". A parameter starts with the ':' character, and ends with a
- "/hello/*name" will fill RouteParams with a glob under the key "name".
  The value will be everything that occurs in place of '*name' until
  the end of the url path.

type Config Uses

type Config struct {
    Server struct {
        Address  string
        Port     int
        CertFile string `gcfg:"cert-file"`
        KeyFile  string `gcfg:"key-file"`
        Devel    bool
    Renderer struct {
        Base string
        Dir  string
    Dispatcher struct {
        Middleware []string
    Static struct {
        Dir      string
        Expires  string
        Prefix   string
        Index    string
        FileList bool `gcfg:"file-list"`
    Session struct {
        Dir             string
        Secret          string
        Cipher          string   // optional: 16, 24 or 32 bytes, base64 encoded
        MaxAge          string   `gcfg:"max-age"`
        CleanupInterval string   `gcfg:"cleanup-interval"`
        CleanupMaxAge   string   `gcfg:"cleanup-max-age"`
        IgnoreURLPrefix []string `gcfg:"ignore-url-prefix"`
    I18n struct {
        Dir              string
        Languages        []string `gcfg:"language"`
        FallbackLanguage string   `gcfg:"fallback-language"`
        IgnoreURLPrefix  []string `gcfg:"ignore-url-prefix"`
    Sitemap struct {
        LocPrefix        string `gcfg:"location-prefix"`
        RelativeLocation string `gcfg:"relative-location"`

func GetConfig Uses

func GetConfig(c context.Context) Config

GetConfig is a helper function for getting the current config from the request context.

func ParseConfig Uses

func ParseConfig(cfg ...string) (Config, error)

ParseConfig reads the given string, merging it with the default configuration. If no path is given, the default configuration is returned. During the merge, the default configuration slice data is removed, thus only the provided configuration's slices are used.

func ReadConfig Uses

func ReadConfig(path ...string) (Config, error)

ReadConfig reads the given file path, merging it with the default configuration. If no path is given, the default configuration is returned. During the merge, the default configuration slice data is removed, thus only the provided configuration's slices are used.

type Controller Uses

type Controller interface {
    Handler(context.Context) http.Handler

In general, a controller is a simple wrapper around an http.HandlerFunc. The Handler method recieves the context, which may then be either stored within the implementing type, or closed over when creating the HandlerFunc.

type Dispatcher Uses

type Dispatcher struct {
    Pattern     string
    Host        string
    Context     context.Context
    Config      Config
    Logger      Logger
    Renderer    renderer.Renderer
    Controllers []Controller
    // contains filtered or unexported fields

Dispatchers are responsible for calling controller handlers for a particular request path, passing it through middleware chain for each request. The middleware order can be configured via the server configuration. Multiple dispatchers may be created, and each one is defined by a ServerMux root pattern. The pattern must end in a '/'.

func GetDispatcher Uses

func GetDispatcher(c context.Context) *Dispatcher

GetDispatcher returns the request dispatcher.

func NewDispatcher Uses

func NewDispatcher(pattern string, c Config) Dispatcher

NewDispatcher creates a dispatcher for the given base pattern and config.

func (*Dispatcher) Handle Uses

func (d *Dispatcher) Handle(c Controller)

Handle registers the provided pattern controller.

func (*Dispatcher) Initialize Uses

func (d *Dispatcher) Initialize()

Initialize creates all configured middleware handlers, producing a chain of functions to be called on each request. Initializes and registers all handled controllers. This function is called automatically by the Server object, when its ListenAndServe method is called. It should be called directly before calling http.Handle() using the dispatcher when the Server object is not used.

func (Dispatcher) Middleware Uses

func (d Dispatcher) Middleware(name string) (Middleware, bool)

Middleware returns a registered middleware based on the given name.

func (Dispatcher) NameToPath Uses

func (d Dispatcher) NameToPath(name string, method Method, params ...RouteParams) string

NameToPath returns a url path, mapped to the given route name. A method should be specified to further narrow down the search. If more than one methods are matched, the first path is returned. Finally, an optional RouteParams object may be given, to replace any path parameters with their values in the given map. The empty string is returned if no route is found for the given name. The root dispatcher pattern is always prepended to any found path.

func (*Dispatcher) RegisterMiddleware Uses

func (d *Dispatcher) RegisterMiddleware(mw Middleware)

RegisterMiddleware registers the given middleware. If its name, derived from the type itself, is present within the dispatcher's middleware configuration, it will be used in that position, otherwise it will be added to the end of the chain, closest to the controller handler. Middleware, supplied by webfw may also be registered in this manner, if a more fine-grained configuration is desired.

func (Dispatcher) RequestRoute Uses

func (d Dispatcher) RequestRoute(r *http.Request) (Route, RouteParams, bool)

RequestRoute returns the route object and params associated with the supplied request.

func (Dispatcher) ServeHTTP Uses

func (d Dispatcher) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP fulfills the net/http's Handler interface.

type Logger Uses

type Logger interface {
    Fatal(v ...interface{})
    Fatalf(format string, v ...interface{})
    Fatalln(v ...interface{})

    Print(v ...interface{})
    Printf(format string, v ...interface{})
    Println(v ...interface{})

    Info(v ...interface{})
    Infof(format string, v ...interface{})
    Infoln(v ...interface{})

    Debug(v ...interface{})
    Debugf(format string, v ...interface{})
    Debugln(v ...interface{})

The logger interface provides some common methods for outputting messages. It may be used to exchange the default log.Logger error logger with another provider.

func GetLogger Uses

func GetLogger(c context.Context) Logger

GetLogger returns the error logger, to be used if an error occurs during a request.

type Match Uses

type Match struct {
    RouteMap   RouteMap
    Params     RouteParams
    ReverseURL map[Method]string

type Method Uses

type Method int
const (
    MethodGet Method = 1 << iota
    MethodAll Method = MethodGet | MethodPost | MethodPut | MethodDelete | MethodPatch | MethodHead

type MethodIdentifierTuple Uses

type MethodIdentifierTuple struct {
    Pattern    string
    Method     Method
    Identifier string

type Middleware Uses

type Middleware interface {
    Handler(http.Handler, context.Context) http.Handler

The middleware interface defines a method which receives a parent http.Handler and the context object. It has to return a regular http.Handler.

type MultiPatternController Uses

type MultiPatternController interface {
    Patterns() []MethodIdentifierTuple

A MultiPatternController may be used in places where a single controller handles more than one patterns. The Patterns method should return a map, whose keys are the patterns to be matched, and the values are a tuple of Method and some pattern identifier, the later of which will be stored in the context. The regular Pattern, Method and Name methods will not be called.

type PatternController Uses

type PatternController interface {
    Pattern() string

    Method() Method
    Name() string

type Route Uses

type Route struct {
    Pattern    string
    Method     Method
    Handler    http.Handler
    Name       string
    Controller Controller

type RouteMap Uses

type RouteMap map[Method]Route

type RouteParams Uses

type RouteParams map[string]string

func GetParams Uses

func GetParams(c context.Context, r *http.Request) RouteParams

GetParams returns the current request path parameters from the context.

type Server Uses

type Server struct {
    Config  Config
    Address string
    Port    int
    // contains filtered or unexported fields

Server is a helper object to handle dispatchers through the standard http.ListenAndServe and http.Handle interface. The address and port can be set through the configuration

func NewServer Uses

func NewServer(confpath ...string) Server

NewServer creates a server with an optional path to a configuration file.

func NewServerWithConfig Uses

func NewServerWithConfig(conf Config) Server

NewServerWithConfig creates a server with the given configuration.

func (*Server) Dispatcher Uses

func (s *Server) Dispatcher(pattern string) *Dispatcher

Dispatcher returns a dispatcher registered for a given base pattern. If no dispatcher exists for the given pattern, a new one is created.

func (Server) ListenAndServe Uses

func (s Server) ListenAndServe() error

ListenAndServe initializes the registered dispatchers and calls the http.ListenAndServe function for the current server configuration

type SitemapController Uses

type SitemapController interface {
    Sitemap(context.Context) []SitemapItem

The sitemap controller provides an additional Sitemap method that returns a slice of SitemapItems which consist of the url of the controller, relative to the dispatcher, the last modification time, the change frequency, and the priority.

type SitemapFrequency Uses

type SitemapFrequency string

type SitemapItem Uses

type SitemapItem struct {
    Loc        string
    LastMod    time.Time
    ChangeFreq SitemapFrequency
    Priority   float64

type StandardLogger Uses

type StandardLogger struct {

func NewStandardLogger Uses

func NewStandardLogger(out io.Writer, prefix string, flag int) StandardLogger

func (StandardLogger) Debug Uses

func (st StandardLogger) Debug(v ...interface{})

func (StandardLogger) Debugf Uses

func (st StandardLogger) Debugf(format string, v ...interface{})

func (StandardLogger) Debugln Uses

func (st StandardLogger) Debugln(v ...interface{})

func (StandardLogger) Info Uses

func (st StandardLogger) Info(v ...interface{})

func (StandardLogger) Infof Uses

func (st StandardLogger) Infof(format string, v ...interface{})

func (StandardLogger) Infoln Uses

func (st StandardLogger) Infoln(v ...interface{})

type Trie Uses

type Trie struct {
    // contains filtered or unexported fields

Trie is an object that stores routes in a prefix tree, and allows for an efficient lookup afterwards. The route paths may contain named route parameters and globs. The parameters are defined as ":key" inside the route path, where a piece of a subsequent request path will be extracted where such a parameter occurs. The value will be the text under a '/' or the end of the request path. A glob is similar to a parameter. It can be defined with "*key", the leading '*' being the different between it and parameters, and it will assing the rest of the request path as the glob value.

func NewTrie Uses

func NewTrie() *Trie

NewTrie creates a new Route trie, for efficient lookup of routes and names.

func (*Trie) AddRoute Uses

func (t *Trie) AddRoute(route Route) error

AddRoute adds the given route to the trie.

func (*Trie) Lookup Uses

func (t *Trie) Lookup(path string, method Method) (Match, bool)

Lookup searches for routes registered for the given path and method, and returns then in the form of a Match object

func (*Trie) LookupNamed Uses

func (t *Trie) LookupNamed(name string, method Method, params ...RouteParams) (Match, bool)

LookupNamed searches for routes registered under the given name



Package webfw imports 20 packages (graph) and is imported by 1 packages. Updated 2016-07-22. Refresh now. Tools for package owners.