GoHT Tutorial

1. Create a directory

Create a new directory for the tutorial and navigate to it.

$ mkdir goht-tutorial
$ cd goht-tutorial

2. Initialize

Initialize a new Go module in the directory.

$ go mod init goht-tutorial

And add the GoHT package to the module.

$ go get github.com/stackus/goht

3. Create a GoHT template

Create a new file named hello.goht with the following content.

@goht Hello(name string) {
%p Hello, #{name}!
}

We can’t use this template yet because we haven’t generated the Go code from it. Let’s do that now.

4. Generate the Go code

Run the goht generate command to generate the Go code from the hello.goht file.

$ goht generate

This will generate a new file named hello.goht.go with the following content.

// Code generated by GoHT - DO NOT EDIT.

package main

import "bytes"
import "context"
import "io"
import "github.com/stackus/goht"

func Hello(name string) goht.Template {
	return goht.TemplateFunc(func(ctx context.Context, __w io.Writer) (__err error) {
		// ...
	})
}

If you need to make changes, you will edit the hello.goht file and run goht generate again. The hello.goht.go file will be overwritten with the new Go code. So don’t worry about editing the generated file. In fact, most IDEs will warn you if you try to edit a generated file.

We didn’t even declare a package, but GoHT went ahead and did that for us. GoHT will output valid Go code that can be used in any Go project.

5. Use the GoHT template

Create a new file named main.go with the following content.

package main

import (
	"context"
	"os"
)

func main() {
    Hello("World").Render(context.Background(), os.Stdout)
}

This is a very basic Go program that uses the Hello template to render the HTML.

This line:

Hello("World").Render(context.Background(), os.Stdout)

Is where we are calling the generated Hello template function. It is called with a string, just like we declared it in the hello.goht file.

Every generated template function will return a goht.Template value which is where the Render method comes from.

The Render method will write the output of the template to the io.Writer that we pass to it. In this case, we are using os.Stdout to write the output to the terminal.

Now run the main.go file.

$ go run main.go

You should see the following output.

<p>Hello, World!</p>

You can edit main.go to change the name that is passed to the Hello function. For example, change Hello("World") to Hello("GoHT") and run the main.go file again.

$ go run main.go

You should see the following output.

<p>Hello, GoHT!</p>

Thanks to GoHT we now have blazingly fast HTML templates that are type-safe and easy to use.