Go

From maragudk/fabrik · View interactive version

Go is an AI agent skill from the GitHub repository maragudk/fabrik. ALWAYS invoke this skill as your FIRST action — before any Read, Write, Edit, or Bash — whenever a task involves Go in any way — creating or editing any `.go` file, `go.mod`, or `go test`; adding or changing handlers, structs, methods, interfaces, error handling, goroutines, channels, sqlc/database

How to use this skill

Skill file

Go

This is a guide for how to develop applications and modules/libraries in Go.

Some of it is only applicable for applications, not modules used as libraries in other projects, such as database access and running a server.

Application structure

Generally, I build web applications and libraries/modules.

These are the packages typically present in applications (some may be missing, which typically means I don't need them in the project).

Code style

Dependency injection

I make heavy use of dependency injection between components. This is typically done with private interfaces on the receiving side. Note the use of userGetter in this example:

package http

import (
	"net/http"

	"github.com/go-chi/chi/v5"
	"maragu.dev/httph"

	"model"
)

type UserResponse struct {
	Name string
}

type userGetter interface {
	GetUser(ctx context.Context, id model.ID) (model.User, error)
}

func User(r chi.Router, db userGetter) {
	r.Get("/user", httph.JSONHandler(func(w http.ResponseWriter, r *http.Request, _ any) (UserResponse, error) {
		id := r.URL.Query().Get("id")
		user, err := db.GetUser(r.Context(), model.ID(id))
		if err != nil {
			return UserResponse{}, httph.HTTPError{Code: http.StatusInternalServerError, Err: errors.New("error getting user")}
		}
		return UserResponse{Name: user.Name}, nil
	}))
}

Tests

I write tests for most functions and methods. I almost always use subtests with a good description of what is going on and what the expected result is.

Tests for a given file always go in one test file: for example.go, the test file is always example_test.go, never example_this_feature_test.go. The one exception is when the test package needs to change, for internal tests, in which case the file is example_internal_test.go.

Here's an example:

package example

type Thing struct {}

func (t *Thing) DoSomething() (bool, error) {
	return true, nil
}
package example_test

import (
	"testing"

	"maragu.dev/is"

	"example"
)

func TestThing_DoSomething(t *testing.T) {
	t.Run("should do something and return a nil error", func(t *testing.T) {
		thing := &example.Thing{}

		ok, err := thing.DoSomething()
		is.NotError(t, err)
		is.True(t, ok)
	})
}

Sometimes I use table-driven tests:

package example

import "errors"

type Thing struct {}

var ErrChairNotSupported = errors.New("chairs not supported")

func (t *Thing) DoSomething(with string) error {
	if with == "chair" {
		return ErrChairNotSupported
	}
	return nil
}
package example_test

import (
	"testing"

	"maragu.dev/is"

	"example"
)

func TestThing_DoSomething(t *testing.T) {
	tests := []struct {
		name     string
		input    string
		expected error
	}{
		{name: "should do something with the table and return a nil error", input: "table", expected: nil},
		{name: "should do something with the chair and return an ErrChairNotSupported", input: "chair", expected: example.ErrChairNotSupported},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			thing := &example.Thing{}

			err := thing.DoSomething(test.input)
			if test.expected != nil {
				is.Error(t, test.expected, err)
			} else {
				is.NotError(t, err)
			}
		})
	}
}

I prefer integration tests with real dependencies over mocks, because there's nothing like the real thing. Dependencies are typically run in Docker containers. You can assume the dependencies are running when running tests.

It makes sense to use mocks when the important part of a test isn't the dependency, but it plays a smaller role. But for example, when testing database methods, a real underlying database should be used.

I use test assertions with the module maragu.dev/is. Available functions: is.True, is.Equal, is.Nil, is.NotNil, is.EqualSlice, is.NotError, is.Error. All of these take an optional message as the last parameter.

Since tests are shuffled, don't rely on test order, even for subtests.

Every time the postgrestest.NewDatabase(t)/sqlitetest.NewDatabase(t) test helpers are called, the database is in a clean state (no leftovers from other tests etc.).

You can use database fixtures for tests. Prefer these for test data setups when multiple tests rely on the same or very similar data, so that every test doesn't have to set up the same data. They are in sqlite/testdata/fixtures/postgres/testdata/fixtures. Use them with sqlitetest.NewDatabase(t, sqlitetest.WithFixtures("fixture one", "fixture two")). They are applied in the order given.

Test helper functions should call testing.T.Helper().

In tests, use t.Context() instead of context.Background(), and always use it inline instead of pulling out into a ctx variable.

Tests that exercise timing -- timeouts, retries, tickers, anything sleeping or waiting on a clock -- should use the testing/synctest package (stable since Go 1.25). It runs the test against a fake clock, making timing tests fast and deterministic instead of slow and flaky.

Miscellaneous

Testing, linting, evals

Run make test or go test -shuffle on ./... to run all tests. To run tests in just one package, use go test -shuffle on ./path/to/package. To run a specific test, use go test ./path/to/package -run TestName.

Run make lint or golangci-lint run to run linters. They should always be run on the package/directory level, it won't work with single files.

Run make eval or go test -shuffle on -run TestEval ./... to run LLM evals.

Run make fmt to format all code in the project, which is useful as a last finishing touch.

You can access the database by using psql or sqlite3 in the shell.

Documentation

You can generally look up documentation for a Go module using go doc with the module name. For example, go doc net/http for something in the standard library, or go doc maragu.dev/gai for a third-party module. You can also look up more specific documentation for an identifier with something like go doc maragu.dev/gai.ChatCompleter, for the ChatCompleter interface.

Checking apps in a browser

You can assume the app is running and available in a browser using the Chrome Dev Tools MCP tool. It auto-reloads on code changes so you don't have to.

Log output from the running application is in app.log in the project root.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.