Building a simple webapp

The Golang standard library has all that’s needed to write simple webapps.

Here’s a brief overview of how to get a webapp running. The bottom of this article describes how to install the code using go install if one wishes to get a head-start.

Setting up a Golang webapp

Inside of $GOPATH/src/bitbucket.org/theandruu/go-public, make a new directory to contain the web application, named simple-webapp and a file inside, named webapp.go:

> mkdir simple-webapp && cd simple-webapp
> touch webapp

Set up the template directory

Inside the simple-webapp directory, make a directory to contain our HTML templates, and inside that a new file named theme.html:

> mkdir templates
> touch theme.html

Open theme.html and insert the following content:

<div>
    <p>Hello, {{printf "%s" .Name}}!
    </p>
</div>

At this point, our setup should look like inside the simple-webapp folder:

> pwd
$GOPATH/src/bitbucket.org/theandruu/go-public/simple-webapp
> tree
.
├── templates
│   └── theme.html
└── webapp.go

Writing the webapp

Edit the file webapp.go to look like this:

package main

import (
    "fmt"
    "html/template"
    "net/http"
    "regexp"
)

var templates = template.Must(template.ParseFiles("templates/theme.html"))
var validPath = regexp.MustCompile("^/(hello)/([a-zA-Z0-9 ]+)$")

// A Message to print to our screen
type Message struct {
    Name string
}

func viewHandler(w http.ResponseWriter, r *http.Request) {
    splitPath := validPath.FindStringSubmatch(r.URL.Path)
    if splitPath == nil {
        // Only handle pages we expect based on our 'validPath' variable
        fmt.Printf("Unable to find name param in %s\n", r.URL.Path)
        http.NotFound(w, r)
        return
    }

    // Name param is the 3rd element in the splice (index 2)
    message := Message{Name: splitPath[2]}

    // Pass a pointer to our message object
    templates.ExecuteTemplate(w, "theme.html", &message)
}

func main() {
    http.HandleFunc("/hello/", viewHandler)
    http.ListenAndServe(":8080", nil)
}

Run the application

From the simple-webapp directory, issue the command:

> go build && ./simple-webapp

Then direct your browser to http://localhost:8080/hello/cruel world.

Try changing the URL in the browser’s address bar to contain a different message.

Quick explanation of the code

The main() function tells the http library to listen for requests with a path beginning with /hello with our viewHandler on port 8080.

The viewHandler() function:

Lastly, our template inside theme.html formats the HTML message returned as a response based on the Name property of the data it’s given.

And that’s about as simple as it needs to be.

Shutting down

To shut down the server, press Control + C at the Terminal window that’s running the Go command.

Download and run yourself

If you already have Golang on your system, you can install the program with:

> go install bitbucket.org/theandruu/go-public/simple-webapp
# Must 'cd' to the source directory so our 'templates' path is relative
> cd $GOPATH/src/bitbucket.org/theandruu/go-public/simple-webapp
> simple-webapp
◀   Sharing code Debugging Golang   ▶