Web.go tutorial

Getting started

For installation insructions, check out the quickstart guide

This is the hello world web application, written in Go, which this tutorial uses:

package main

import (
    "web"
)

func hello(val string) string { return "hello " + val }

func main() {
    web.Get("/(.*)", hello)
    web.Run("0.0.0.0:9999")
}

URL Handling

The most important part of a web application is knowing what to do given a url. Web.go provides several methods of adding url handlers that are based on the route. These include

There are also methods web.Delete and web.Put with a similar signature

Route handlers

In the hello example above, the "/(.*)" url pattern is matched to the following function:

func hello(val string) string { return "hello " + val }

In that example, everything after the "/" is passed to the argument val in the hello function. A handler function is required to have the same number of arguments as regular expression groups in its url pattern.

Although handlers usually return a string, web.go also accepts route handlers that have no return value. These methods are responsible for writing data to the client:

func hello(ctx *web.Context, val string) { ctx.WriteString ( "hello " + val) }

Writing to the context variable is explained in a later section.

The web.Context

There's an optional first variable in every route handler - a pointer to web.Context. This variable serves many purposes -- it contains information about the request, and it provides methods to control the http connection.

Here is a brief summary of web.Context:

Methods on web.Context:

Templates

Web.go doesn't include a templating library. However, there are several good ones available, such as mustache.go. The template package in Go is not recommended for web.go because it doesn't allow templates to be embedded within each other, which causes a lot of duplicated text.

Shared hosts

Web.go provides methods to run web applications using the SCGI or FastCGI protocols. This enables web.go apps to run in shared hosts environments.

These methods are similar to web.Run:

For instance, to serve the hello example above running Scgi, just write the following:

func main() {
    web.Get("/(.*)", hello)
    web.RunScgi("0.0.0.0:6580")
}

Next you need to configure your web server to pass requests along to port 6580.