gogo

module
v0.4.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2026 License: Apache-2.0

README

Save forms like your father did

WARN: Work in progress, incompatible changes or force push can happen any time

Packages

Forms

Forms expect htmx to be set up for the application. The principle there is that we want to keep things simple, adding a form to a website should be as trivial as it can be. The simplest thing is to avoid touching the javascript in the first place, right?

With this approach you get custom validation, full control over templates and an SPA-like behavior without related headaches at the same time.

1. Define a Form

package forms

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
)

type SettingsGeneralFormInput struct {
	Timezone string `form:"timezone"`
}

type SettingsGeneralForm struct {
	*FormBase[SettingsGeneralFormInput]
	User     *core.User
	Settings *settings.Service
}

func SettingsGeneralFormNew(svc *settings.Service, u *core.User) Form {
	var form Form = &SettingsGeneralForm{
		FormBase: &FormBase[SettingsGeneralFormInput]{
			Name:         "settings_general",
			FormTemplate: "form--settings-general.html",
			Input:        &SettingsGeneralFormInput{},
			ExtraTemplateData: map[string]interface{}{
				"User": u,
			},
		},
		User:     u,
		Settings: svc,
	}

	return form
}

func (f *SettingsGeneralForm) Validate(c *gin.Context) error {
	if f.Input.Timezone == "" {
		f.AddError("timezone", "timezone is required")
		return ErrValidationFailed
	}

	return nil
}

// Save runs outside any transaction: the form holds the service it needs,
// and the service owns its transactions.
func (f *SettingsGeneralForm) Save(c context.Context) (FormSaveAction, error) {
	if err := f.Settings.SetTimezone(c, f.User, f.Input.Timezone); err != nil {
		return nil, errors.Wrapf(err, "failed to save the timezone")
	}

	return f.FormBase.Save(c)
}

2. Define gin handlers

	controls.GET("/settings", func(c *gin.Context) {
		userData := auth.GetUserData(c)

    // gather your data there
		c.HTML(http.StatusOK, "settings.html", web.Settings(c, db, &userData))
	})

	controls.POST("/form/save_settings", func(c *gin.Context) {
		userData := auth.GetUserData(c)
		dbUser := userData.DBUser

		form := forms.SettingsGeneralFormNew(settingsService, dbUser)

		forms.DefaultHandler(c, logger, form)
	})
3. Define templates

The trick is to have a form template as a partial and include it from the page. All the helpers in the template below are not included into the package. Roll your own!

settings.html
{{ template "header.html" . }}

{{ $user := .User.DBUser }}
<div class="uk-container">
  <h1 class="uk-heading-medium">Settings</h1>

  <div class="uk-flex-center uk-grid">
    <div class="uk-card uk-card-default uk-card-body uk-width-2-3@m">
      <h3 class="uk-card-title">General</h3>
      {{ template "form--settings-general.html" toMap "User" $user }}
    </div>
  </div>
</div>

{{ template "footer.html" . }}
form--settings-general.html
{{ if .FormSaved }}
  {{ template "partial--success-message.html" toMap "Message" "Settings have been saved" }}
{{ end }}

<form class="uk-form-stacked" method="POST"
  action="{{ link "form_save_settings" }}"
  hx-post="{{ link "form_save_settings" }}"
  hx-swap="outerHTML"
  >

  <div class="uk-margin">
    <label class="uk-form-label" for="form-stacked-text">Submit</label>
    <div class="uk-form-controls">
      {{ if and .Errors (ne .Errors.timezone "") }}
      <div class="uk-text-meta uk-text-danger">{{ .Errors.timezone }}</div>
      {{ end }}
      <select class="uk-select" name="timezone">
        {{ $selected_tz := .User.Timezone }}
        {{ if (and .Input .Input.Timezone) }}
          {{ $selected_tz = .Input.Timezone }}
        {{ end }}

        {{ range tzlist }}
          <option value="{{ . }}" {{ if eq . $selected_tz }}selected{{ end }}>{{ . }}</option>
        {{ end }}
      </select>
    </div>
  </div>

  <div class="uk-margin">
    <button type="submit" class="uk-button uk-button-primary uk-button-large">Save settings</button>
  </div>
</form>
Settings

settings sits on top of go-flags. Declare every setting once, with paired long: and env: tags, and parse with settings.Parse instead of ParseArgs:

type Config struct {
    DatabaseURL string          `long:"database-url" env:"DATABASE_URL" required:"true"`
    SessionSalt settings.Secret `long:"session-salt" env:"SESSION_SALT" required:"true"`
    Mailjet     mjconfig.Config `group:"Mailjet" namespace:"mj" env-namespace:"MJ"`
}

var cfg Config
p := flags.NewParser(&cfg, flags.HelpFlag) // not flags.Default: it prints go-flags' own error first
if _, err := settings.Parse(p, os.Args[1:]); err != nil {
    // "required settings are missing or empty: --database-url or $DATABASE_URL, ..."
}
  • A required setting whose environment variable exists but is empty counts as missing (go-flags alone accepts it), and the error names every missing setting by flag and variable. It fails before any command runs.
  • settings.Secret redacts itself in fmt, slog and JSON; Reveal() returns the value.
Mail

sender.Sender delivers a sender.Mail. The Mailjet sender takes a sender/mailjet/config.Config; its BaseURL (--mj.api-base, MJ_API_BASE in the group above) points it at a Mailjet mock such as tommy in development and tests. Mail.Headers carries extra headers, such as the RFC 8058 List-Unsubscribe and List-Unsubscribe-Post; From, To, Cc, Bcc and Subject stay in their own fields. Queueing mail in the database, so it is sent only if a transaction commits, is the application's job.

Pages and errors

Services return the errors of apperr (ErrNotFound, ErrForbidden, ErrNeedsLogin, ErrConflict, ValidationError), wrapped with a reason. util/ginhelpers maps them to statuses (Status) and answers requests with HTML, HTMLError and API. Configure it per router:

r.Use(ginhelpers.Configure(ginhelpers.Options{
    RedirectToLogin: auth.RedirectToLogin, // pages that fail with ErrNeedsLogin
    ShowErrors:      !production,          // error text in responses
}))

util/ginhelpers/csrf checks the session's CSRF token in the X-CSRFToken header or the header_csrf form field.

Sessions

sessions/pgstore stores gin sessions in PostgreSQL. It replaces antonlindstrom/pgstore and reads the rows and cookies that pgstore wrote, so switching keeps everyone logged in.

Why not antonlindstrom/pgstore
  • It is unmaintained: the last commit is from 2022.
  • It creates its table when the application starts, outside the application's migrations.
  • It imports lib/pq, a second PostgreSQL driver next to the pgx that gogo apps use.
  • Its cleanup of expired rows is a goroutine the application has to remember to start. Without it the table only grows.
Differences from antonlindstrom/pgstore
  • Same data. The table, the cookie (the session ID, encoded with securecookie) and the row's data (the session values, encoded with the same codecs) are unchanged. A test reads a cookie and a row written the way pgstore writes them.
  • The table comes from a migration, which ships with the package (below). The store never creates it.
  • Expired rows read as missing. pgstore relied only on securecookie's timestamp in the cookie.
  • A bad or tampered cookie, a missing row or undecodable data give a fresh session with a new ID, not an error. gin-contrib only logs a store error, so an application sees the same result either way.
  • MaxAge 0 (a browser-session cookie) keeps the row for DefaultMaxAge. pgstore wrote such a row as already expired, so its cleanup deleted it.
  • Regenerate(ctx, session) starts a fresh session at login and logout, against session fixation.
  • pgstore's special created_on and expires_on session values are not read.
  • Queries take the request's context; there is no lib/pq, sqlx or pkg/errors.
The migration

The store's table is a sql-migrate migration in sessions/pgstore/migrations/. Copy it into your application's migrations directory once, commit it, and it runs with your other migrations (the sql-migrate command, fly.toml's release_command, and testcontainers/postgres in tests):

go run github.com/can3p/gogo/sessions/pgstore/cmd/pgstore-migrations -dir migrations
  • The copy is named like a migration made with sql-migrate new at that moment, e.g. 20270304050607-gogo-pgstore-0001-http-sessions.sql, so it runs after your existing migrations. If your directory holds a migration dated later than now, the copy is dated one second after it.
  • A copy is recognized by the name after its timestamp, so running the command again writes nothing. A copy that was edited is reported, not overwritten.
  • A gogo upgrade that changes the table adds a new file. Run the command again to copy it, with a new timestamp.
  • The migration uses IF NOT EXISTS, so where antonlindstrom/pgstore already created the table it only records itself.

Guard against a missed copy with a test, so CI fails until the command has run:

func TestSessionMigrationsInstalled(t *testing.T) {
	require.NoError(t, pgstore.CheckMigrations("../../migrations"))
}

pgstore-migrations -check does the same from a shell. An application that runs migrations from Go instead can read the files from pgstore.Migrations (an embed.FS).

Usage
store := pgstore.New(db, []byte(cfg.SessionSalt.Reveal()))
go store.Cleanup(ctx, pgstore.DefaultCleanupInterval, logger) // deletes expired rows until ctx is done
r.Use(ginsessions.Sessions("session", store))

// at login and logout, against session fixation:
if err := pgstore.Regenerate(c.Request.Context(), ginsessions.Default(c)); err != nil { ... }
Testcontainers

The testcontainers/postgres package gives each integration test a real, migrated, empty PostgreSQL database of its own, using testcontainers-go.

import (
    "os"
    "testing"

    "github.com/can3p/gogo/testcontainers/postgres"
)

func TestMain(m *testing.M) {
    code := m.Run()
    _ = postgres.Cleanup() // optional: stop the container right away
    os.Exit(code)
}

func TestSomething(t *testing.T) {
    t.Parallel()

    db := postgres.New(t, postgres.WithMigrationsDir("../../migrations"))

    // db.DB is a *sql.DB, db.URL the connection string.
    // The database is dropped when the test ends.
}

Features:

  • One container per test binary, shared by all tests
  • Migrations are applied once into a template database; each test gets a copy made with CREATE DATABASE ... TEMPLATE, so setup cost does not grow with the number of migrations
  • Unique database per test, safe with t.Parallel()
  • The migrations directory is required and checked, so a wrong path fails loudly instead of running tests against an empty schema
  • Migrations are recorded in the migrations table by default (WithMigrationsTable to change), matching what the sql-migrate CLI reads from dbconfig.yml rather than the Go API's gorp_migrations default
  • WithImage overrides the default postgres:16-alpine image
  • Uses the lib/pq driver; URL is a standard postgres:// URL, so it can be opened with pgx or passed to a subprocess

NewTestDB(Options{...}) still works but is deprecated in favour of New.

Directories

Path Synopsis
Package apperr is the error vocabulary an application's services share with its transports.
Package apperr is the error vocabulary an application's services share with its transports.
sessions
pgstore
Package pgstore stores gin sessions (github.com/gin-contrib/sessions, on gorilla/sessions) in PostgreSQL.
Package pgstore stores gin sessions (github.com/gin-contrib/sessions, on gorilla/sessions) in PostgreSQL.
pgstore/cmd/pgstore-migrations command
Command pgstore-migrations copies the migrations of gogo's sessions/pgstore into an application's sql-migrate migrations directory:
Command pgstore-migrations copies the migrations of gogo's sessions/pgstore into an application's sql-migrate migrations directory:
Package settings holds the helpers an application needs on top of github.com/jessevdk/go-flags: every setting is an option with paired `long:` and `env:` tags, required settings fail at startup and name their environment variable, and credentials are Secrets that don't print.
Package settings holds the helpers an application needs on top of github.com/jessevdk/go-flags: every setting is an option with paired `long:` and `env:` tags, required settings fail at startup and name their environment variable, and credentials are Secrets that don't print.
testcontainers
postgres
Package postgres gives an integration test a real, migrated, empty PostgreSQL database of its own.
Package postgres gives an integration test a real, migrated, empty PostgreSQL database of its own.
util
ginhelpers
Package ginhelpers answers gin requests with the result of a service call: a page, a JSON API response, or the status an apperr error maps to.
Package ginhelpers answers gin requests with the result of a service call: a page, a JSON API response, or the status an apperr error maps to.
ginhelpers/csrf
Package csrf rejects state-changing requests that don't carry the session's CSRF token, in the X-CSRFToken header or the header_csrf form field.
Package csrf rejects state-changing requests that don't carry the session's CSRF token, in the X-CSRFToken header or the header_csrf form field.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL