Build your first router in Go

Add patterns to a Go router, and find the data of the pattern that best matches each query.

In this tutorial we build a router of sales-tax rates in Go, the same router as Build your first router builds in JavaScript. We add a general rate and a special case, and see the router choose between them. It takes about 10 minutes.

You need Go 1.24 or later. Make a module, and add patrun to it:

go mod init example.com/tax
go get github.com/rjrodger/patrun/go

Write the program #

A Go router matches maps of strings, and holds a *string as each pattern's data. Write this in main.go:

package main

import (
	"fmt"

	patrun "github.com/rjrodger/patrun/go"
)

func s(v string) *string { return &v }

func main() {
	tax := patrun.New()
	tax.Add(map[string]string{"country": "IE"}, s("23%"))
	tax.Add(map[string]string{"country": "IE", "type": "books"}, s("0%"))

	rate, ok := tax.Find(map[string]string{"country": "IE", "type": "books"})
	fmt.Println(*rate, ok) // 0% true

	rate, ok = tax.Find(map[string]string{"country": "IE", "type": "food"})
	fmt.Println(*rate, ok) // 23% true

	_, ok = tax.Find(map[string]string{"country": "FR"})
	fmt.Println(ok) // false
}

Run it:

go run .

It prints 0% true, then 23% true, then false.

s makes a pointer to a string, which Add takes as the data. Find gives the data and true when a pattern matches, and nil and false when none does.

What the router did #

A sale of books matches both patterns, and the router chose the one with two properties: the most specific pattern wins. A sale of food has no pattern of its own, so it matched the pattern for Ireland alone, and type made no difference. No pattern matches a sale in France.

The JavaScript router gives the same answers to the same patterns, and the Go reference says where the two ports differ.

Next #

The how-to guides show each task in Go after its JavaScript. To list what a router holds, see List the patterns a router holds.

This page describes patrun 9.0.0 for JavaScript and 0.4.0 for Go. Edit this page · This page as Markdown