Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

go

БесплатноБез исполняемых скриптовНе проверен

Guide for how to develop Go apps and modules/libraries. Always use this skill when reading or writing Go code.

maragudkот maragudk★ 49 звёзд на GitHub14 установок в других каталогах

Об этом скилле

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).

  • main: contains the main entry point of the application (in directory cmd/app)
  • model: contains the domain model used throughout the other packages
  • sql/sqlite/postgres: contains SQL database-related logic as well as database migrations (under subdirectory migrations/) and test fixtures (under subdirectory testdata/fixtures/). The database used is either SQLite or PostgreSQL.
  • sqltest/sqlitetest/postgrestest: package used in testing, for setting up and tearing down test databases
  • s3: logic for interacting with Amazon S3 or compatible object stores
  • s3test: package used in testing, for setting up and tearing down test S3 buckets
  • llm: clients for interacting with large language models (LLMs) and foundation models
  • llmtest: package used in testing, for setting up LLM clients for testing
  • http: HTTP handlers for the application
  • html: HTML templates for the application, written with the gomponents library (see https://www.gomponents.com/llms.txt for how to use that if you need to)

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 whats is going on and what the expected result is.

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 the

Полный SKILL.md на GitHub

Установить go в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл go?

Guide for how to develop Go apps and modules/libraries. Always use this skill when reading or writing Go code.

Как установить скилл go?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл go запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить go с