Writing Web Application with Templates

This lesson shows how to build a wiki application which is more detailed than the previous one. To make this application quickly and effectively, a template package is used from the Go standard library.

We'll cover the following

Building a wiki application

The following program is a working web-application for a wiki, which is a collection of pages that can be viewed, edited, and saved in under 100 lines of code. It is the code lab wiki tutorial from the Go site, one of the best Go-tutorials in existence. It is certainly worthwhile to work through the complete code lab to see and better understand how the program builds up. Here, we will give a complimentary description of the program in its totality, from a top-down view.

The program is a web server, so it must be started on the command-line; let’s say on port 3000. The browser can ask to view the content of a wiki-page with a URL, like https://1dkne4jl5mmmm.educative.run/view/page1.

The text of this page is then read from a file and shown on the web page; this includes a hyperlink to edit the wiki page ( https://1dkne4jl5mmmm.educative.run/edit/page1). The edit page shows the contents in a text frame. The user can change the text and save it to its file with a submit button Save; then, the same page with the modified content is viewed. If the page that is asked for viewing does not exist (e.g., https://1dkne4jl5mmmm.educative.run/edit/page999), the program detects this and redirects immediately to the edit-page, so that the new wiki-page can be made and saved.

The wiki-page needs a title and text content. It is modeled in the program by the following struct, where the content is a slice of bytes named Body :

type Page struct {
Title string

Body []byte
}

In order to maintain our wiki-pages outside of the running program, we will use simple text-files as persistent storage.

Get hands-on with 1200+ tech skills courses.