Repository navigation
Releases
v0.10.0
Added
- Exact-schema tag options.
int4(a 4-byte integer,SERIALfor a PostgreSQL key),naive(timestamp without time zone),notnull,default=v(a string, boolean or integer) andunique=name/index=name(explicit index names) let a migration describe an existing database exactly. They are opt-in: a model that uses none generates what it did before. A tag that uses any of them is parsed strictly. See exact schema. - Migration steps
AlterColumnNotNull,AlterColumnDefaultandRenameIndex, an optionalNameonCreateIndex,DropIndexandAlterColumnUnique, and width, time-zone and typed-default fields onAlterColumnType.tango makemigrationsgenerates them for changes to the options above instead of refusing, including an irreversibleint4to bigint widening (which also moves a PostgreSQL sequence tobigint) and anaiveto time-zone widening (values read as UTC). SettingNOT NULLchecks forNULLrows before any DDL. See exact-schema changes. migration.ValidateModels, run bytango.Checkandtango.DumpModels, refuses a foreign key whose width differs from the key it references (MySQL rejects the mix) and an index name used twice in the schema.- A handshake between
tango makemigrationsand the app. The CLI passestango-exact-schema-v1after-tango-dump-models; an app whose models use the new options refuses to dump without it, so an older CLI cannot drop them silently.makemigrationsalso warns when the app'sgo.modrequires tango below v0.10.0.
Changed
- Migration files that use an exact-schema attribute are written under
V2step kinds, which a reader older than v0.10.0 refuses by name. Files that use none are written as before. makemigrationsrefuses a--renameof a field or model with an explicitly named index, and a newnotnullfield with no default on an existing table.
v0.9.0
Added
model.Date, a calendar date with no time of day and no zone. It is a model field with theuniqueandindextags (pkis rejected), stored asDATEon SQLite, PostgreSQL and MySQL. It hasNewDate,MustDate,ParseDate,DateOf,In,AddDays,Compareand the usual accessors, and it marshals as anullor"YYYY-MM-DD"JSON value. Its zero value means no date, and several zero dates are severalNULLvalues under a unique constraint.- Date support across tanGO. The admin shows a date input and parses it strictly, the shell prints and accepts
YYYY-MM-DD, migrations generate adatecolumn, and OpenAPI describes amodel.Datebody value as adatestring that also allowsnull(a zero date marshals asnull), and a query parameter as a non-nullabledatestring. Date supports=,!=, the range operators,IN,IS NULLandIS NOT NULL. admin.error.not_dateis the message a Date field shows for a value that is notYYYY-MM-DD(English fallback "Enter a date as YYYY-MM-DD.").migration.Validaterejects conflicting migration numbers. The registry is invalid when one app registers the same(App, Name)twice, or two names in one app share a leading four-digit number. The same number in two apps is valid.Validatereturnsmigration.ErrConflictingMigrations, wrapped with one deterministic error that lists every conflict. The check reads the registry, not the database, and has no bypass. See the migration numbers and conflicts section of the migrations guide.ProjectStatus.MigrationError(JSONmigrationError) carries a registry conflict. Status andtango tuireport it without failing, and the TUI does not offer to apply migrations while it is set.- Relation loading.
Query.Preloadloads relation fields onto the rowsListandFirstreturn. A relation is a field taggedtango:"belongs_to=Field"(a pointer to a named struct) ortango:"has_many=Field"(a slice of named structs), whereFieldis the foreign key it uses. A dotted name such as"Comments.Author"loads nested levels, at most three segments deep and twenty distinct reads per query.Store.RelatedandStore.RelatedManyare the batch reads underneath, usable on any store, and each writes into a caller-owned map. A relation field is not a column: no migration is generated, andCreateandUpdateignore it. A nested read runs in one read-only REPEATABLE READ transaction; on SQLite it blocks writers for its duration. See loading related rows. model.ModelMeta.Relations,model.RelationMeta,model.ErrInvalidRelationandRegistry.ValidateRelationsdescribe and check the relation fields.Config.CheckrunsValidateRelationsbesideValidateForeignKeys, so a relation whose key does not name a foreign key to its model, or whose key type differs from the primary key type, fails the check.
Changed
- A zero
time.Timeis stored asNULLon SQLite and PostgreSQL, as it already was on MySQL. Before this change SQLite and PostgreSQL wrote year 0001. Only future writes change. A year-0001 row written earlier still reads as the zerotime.Time. Before this change an unset time sorted first on SQLite and PostgreSQL. Now NULL ordering is native to each dialect: in ascending order an unset time sorts first on SQLite and MySQL and last on PostgreSQL. See the upgrade notes for the optional cleanup. Store.QueryandStore.QueryRowreject a zerotime.Timeor zeromodel.Dateargument withErrInvalidQuery, before any SQL runs. Bindnilfor NULL.- A zero
time.Timeor zeromodel.Dateis rejected as a query value.=,!=,>,>=,<,<=and everyINelement returnErrInvalidQuerybefore any SQL runs, and the message namesdb.IsNullanddb.IsNotNull. Code that compared against a zero time to find unset rows must useIsNull. - The admin changelist loads each labelled foreign-key column with one related read per page. Before, it looked up each cell's label on its own, up to 26 reads per foreign-key column on a page. A failed label read is still logged and the column shows the raw keys.
-migrateandmigration.ApplyPendingrefuse a conflicting registry before any database access. Notango_migrationstable is created, and nothing is read or applied. A registry that applied before may now be refused until one migration is renumbered. See upgrading.tango checkreports migration conflicts with configuration failures, in the samecheck failed: ...error.tango makemigrationsrefuses a conflicting registry, exits 1 withtango makemigrations: ..., and writes no files.-tango-dump-modelsrefuses a conflicting registry withcheck failed: ..., whatever other flag is given, and prints no models.-migrate -downis the exception: it is the recovery path, is not subject to this check, and on a fresh database may create the tracking table before it reports that there is nothing to roll back.tango shellruns Yaegi v0.16.2, up from v0.16.1, and now runs a range over an integer (for i := range 3). A range over a function still fails, and stays on the shell's list of Go it cannot run.- Dependencies:
github.com/jackc/pgx/v5v5.12.0,modernc.org/sqlitev1.61.1 andgolang.org/x/netv0.62.0 in the root module;google.golang.org/apiv0.310.0 instorage/gcs.
Fixed
- The admin's phone drawer no longer slides shut when a page loads. A page styled before
nav.jsran animated the drawer from open to closed on load. The drawer now takes its closed place without a transition, and opening and closing animate as before. RollbackLastfails before anyDownon an unorderable tie, and never guesses. When rows sharing the latestapplied_atcannot be ordered, it returnsmigration.ErrUnorderableTiewhere it used to roll back the row with the greatest name. A target registered more than once returnsmigration.ErrAmbiguousRollbackTarget. A tie that can be ordered rolls back as before.
v0.8.1
Added
tango.ErrInvalidBodymatches, witherrors.Is, every errorContext.Bindreturns for a malformed request body. The decoder's error stays reachable througherrors.As.
Changed
- The default database pool keeps up to 256 idle connections, up from 32. With 32, a server handling more than 32 queries at once closed each connection it released and opened a new one for the next request; on PostgreSQL every new connection starts a server process. Measured on a 36-CPU host, single-pet reads at 128 concurrent clients opened about 1,360 PostgreSQL sessions per second and served half the requests per second of 64 clients. The number of open connections is unchanged (unlimited), and a pool bounded with
SetMaxOpenConnsor set withtango.WithDBPoolis left as it was. A server that briefly handles up to 256 concurrent queries now keeps that many PostgreSQL connections open afterwards; passtango.WithDBPoolwithMaxIdleorMaxIdleTimeto hold fewer.
Fixed
- A malformed request body bound with
Context.Bindanswers400, not500. A View that returns theBinderror unhandled now gets400 {"error":"invalid request body"}and no View-error log. A JSON syntax or type error, or an end-of-input error (io.EOF,io.ErrUnexpectedEOF), counts as malformed wherever it comes from: the decoder, a customUnmarshalJSON, or the body reader when a client disconnects mid-body. OtherBindfailures, a body over aMaxBodySizelimit included, keep their answers (500, and413respectively).
v0.8.0
Host upgrade notes for v0.8.0, upgrading from v0.7.0, are in docs/upgrading.md.
Added
- Security headers and a typed Content-Security-Policy.
tango.SecurityHeadersis opt-in middleware that sets a Content-Security-Policy and the companion headersX-Content-Type-Options,Referrer-PolicyandX-Frame-Options, and setsStrict-Transport-Securityover TLS whentango.WithHSTSis given. Installed with no options it applies the strict baseline,tango.StrictCSP(). A policy is atango.CSPbuilt fromtango.Sourcevalues (Self,None,Host,Scheme,Data,Blob,NonceSource, andUnsafeInlineStyleforstyle-src), so there is no raw-string policy. Installs at several tiers (global, group, route, admin) compose as the guide describes: the innermost install's policy is the one sent.tango.CSPNonceandtango.NonceAttrgive a template the request's nonce.admin.ContentSecurityPolicy()is the policy the admin's pages satisfy, composed withadmin.WithMiddleware.swaggerui.WithContentSecurityPolicyserves the Swagger UI page under an application's policy, andswaggerui.Newtakes these options, so a call with no arguments is unchanged. The new API has no effect until an application installs it. See the content security policy guide.
Changed
-
The strict baseline restricts form submissions to the application's own origin.
tango.StrictCSP()now includesform-action 'self', so the Content-Security-Policy sent when no policy option is given gains that directive. The browser refuses a form that posts to another origin under the baseline. An application that posts a form to another origin supplies a policy whoseFormActionlists that origin. -
tango.UnsafeInlineStyle()is valid only instyle-src.tango.WithContentSecurityPolicypanics, when the middleware is built, with a message that names the directive, if the source appears indefault-src,script-srcor any other directive. Before this change the policy rendered'unsafe-inline'in that directive. Upgrade note: a policy that namesUnsafeInlineStyle()outsideStyleSrcnow panics when the middleware is built. Move the source intoStyleSrc. -
The admin phone drawer opens and closes without animation when the operating system asks for reduced motion. The drawer's slide is replaced by an immediate change under
prefers-reduced-motion: reduce. -
The admin changelist row checkboxes are larger click targets. Each row checkbox sits in a label at least 24 CSS pixels square, so a touch on a phone selects the row rather than missing it.
-
The admin's breadcrumb links and the labels beside form checkboxes are at least 24 CSS pixels tall. Both were 20 pixels tall on a phone, below the size a touch reliably hits.
-
The admin's list, form, delete, bulk outcome, sign-in, dashboard and error pages each have their own browser tab title. The title starts with the page's heading, such as "Crud products · tanGO Admin", and the sign-in page reads "Sign in · tanGO Admin". The bulk delete outcome page is titled with its action, "Delete selected".
-
The admin's create and edit forms explain a failed save. A save with more than one problem shows a summary above the first field, headed with the count ("Fix 2 problems to save this book.") and listing each problem as a link to its field. Each link is the field's label followed by its message. Focus moves to the summary when the page renders; a save with one field problem moves focus to that field instead, and the summary is shown for one problem only when it is not tied to a field. Built-in widgets print each field's help text between its label and its control. A host widget keeps the help text beneath its control, unless its own markup prints it. The empty foreign key choice reads "No author selected", the add button beside a foreign key names the target in visible text ("Add new author") after a "+" that is hidden from assistive technology, and Can 8000 cel names the list it returns to.
-
Admin outcomes appear in a status region on every page. After a create, save, delete or bulk delete, the next admin page shows the outcome in one
role="status"region above the content, with a Dismiss control. The outcome is carried in a cookie signed with a key derived from the admin session, so it cannot be forged and is shown only to the session that set it. The page that shows the outcome expires the cookie in the browser; the server also stops accepting a copy of it 300 seconds after it was set. A copy taken before that time is still accepted until then. The bulk delete redirect no longer carries adeletedquery parameter. Upgrade note: a host that read that parameter must read the status region's outcome instead. -
Admin save errors name the field and keep what you typed. A value that is not a number, a date or valid JSON shows a plain message beside its field, and the other values in the form stay as submitted. A duplicate unique value returns 422 with a message beside the field, where it returned a server error before. Upgrade note: a programmatic caller that treated a duplicate-value save as a 500 must expect 422. A foreign key that no longer exists, and a delete the database refuses because other rows still use the row, show a plain message instead of a server error. The raw parser and database text is never shown. Messages come from
admin.*keys with English fallbacks, so a host catalog overrides one key at a time. The sidebar, headings, breadcrumbs and messages name a model with its display noun (admin.OptionsSingularNameandPluralName), not its Go type name. The style guide isadmin/MESSAGE_STYLE.md. -
The JSON and Markdown widgets show their editors without script, and hide what is empty. Without JavaScript the Formatted panel of the JSON field and the Preview panel of a Markdown field are visible, stacked under the editor. The Formatted box and the Preview frame stay hidden until they have content, so the editor is the only visible control. With the script, the tabs show and the inactive panel is hidden as before.
-
The dark header is distinct from the sidebar. The admin header has its own surface token: in the dark theme it is a lighter navy than the sidebar and the page, so the bands read apart. In the light theme the header is opaque white, where it was translucent and blurred before.
-
The widget tabs have a selection edge and a focus ring. The selected tab is marked with a navy edge in the light theme and a cyan edge in the dark theme, and a focused tab shows a ring with an offset. Tab targets are at least 36px tall.
-
On a phone, the form's Save and Cancel buttons are full width. Below 640px each takes the full width of the form, one above the other, with Cancel's text wrapping rather than overflowing.
-
The invalid JSON message is one sentence in the status line. The Formatted view of an invalid document shows the sentence in the field error style, and its box stays empty.
-
The bulk delete bar states its selection, and the dialog names the count. The bar is visible once the script runs. With no row picked, its count slot shows the reason "Select rows to delete them." and Delete selected is disabled and described by that reason; with a row picked, the count shows the selection and the button is enabled. The table's select-all is hidden on a phone, where a "Select all on this page" control in the bar takes its place. The dialog title names the count with singular and plural copy, and lists up to ten names followed by "and N more". The rejected bulk-delete page shows the section's plural name as its heading, the plain reason beneath it, and a "Back to" link. Its breadcrumb current item is "Delete selected".
-
admin.Optionsnames a model's rows for messages. The newSingularNameandPluralNamefields give the noun used in headings, empty states, bulk outcomes and field messages. Unset, the humanized Go name is used. -
The admin widget script no longer uses the
{error}message placeholder. No message the widgets show carries it, so a translation need not keep it. The{count}and{max}placeholders are unchanged. -
The
data-activityanddata-markdown-statusattributes are gone from admin markup. No script or stylesheet in tanGO reads them. Admin HTML is outside the covered API, but a host that styled or selected those attributes needs another selector. -
The admin serves a precompiled stylesheet and no longer loads Tailwind from a CDN. The admin's stylesheet is generated by
scripts/admin-css.shand served from a content-hashed URL. The admin's pages no longer contain inline script, inline style oronclickhandlers: navigation is a hashed script bound with event listeners. The admin's colour tokens and its light and dark selection are unchanged. Upgrade note: host widgets can rely only on the token utilities (text-,bg-,border-andring-for the admin's token names), including their opacity variants such astext-ink/60, which the stylesheet styles at Tailwind's default opacity steps. Other Tailwind utilities need the host's own stylesheet: the admin's stylesheet contains them only because the admin's own templates use them, and a release may remove them. A host widget or template that needs other classes, or relied on Tailwind loading at runtime, ships its own stylesheet from a content-hashed URL. Underadmin.ContentSecurityPolicy()a host widget's inlinestyleattribute or inline event handler is blocked. -
The admin shell is lighter and easier to use with a keyboard and on a phone. The sidebar takes a light tinted ground in the light theme (the card surface in dark) and lists models as soft pills, the current one marked with
aria-current. Every page starts with a skip link to the main content. Edit, delete, new and rejected bulk-delete pages show breadc...
v0.7.0
Added
-
Sequenced realtime frames. A
Logicthat also implementsrealtime.Framerframes every payload admitted to each member of its room with a per-connection sequence: 1 for the join snapshot, then 2, 3 and so on, restarting at 1 on reconnect. The host owns the wire format.Joinfails withrealtime.ErrEmptyFrame(or the wrappedFrameerror) when the framed snapshot is empty or fails, and the failure does not close the existing connection or admit the new peer. Admitted sends fromSnapshotkeep their sequence and are not rolled back; a send whoseFrameerrors or overflows the queue closes the existing connection, which stays closed. ALogicthat does not implementFrameris unchanged. See the realtime guide. -
Google Cloud Storage adapter (experimental, separate module).
storage/gcsis astorage.Storeon Google Cloud Storage, in its own Go module so no cloud SDK reaches a project that does not import it.gcs.Newauthenticates with application-default credentials, workload identity or explicit credentials, andgcs.NewFromClienttakes a client the host built. Writes are create-only and atomic, and a retried write that already committed is confirmed by a per-write token, checksum and size rather than reported as a collision. Experimental: tested against an in-process emulator, not yet against a real bucket. The module is versioned and tagged separately asstorage/gcs/vA.B.C, after the rootv0.7.0tag it requires. See the uploads guide. -
Admin bulk delete.
admin.Options.BulkDeletelets a staff account delete the checked rows of one changelist page after a confirmation dialog. The delete is one all-or-nothing transaction that cascades like a single-row delete, an invalid selection (empty, over a page, a wrongcount, a repeated or non-canonical key) is rejected whole, and each committed delete logs oneadmin.EventBulkDelete(tango.admin.bulk_delete) event withmodel,selected_count(the rows selected, not the database rows a cascade deleted) andusername. It is off by default, needs JavaScript and never spans more than a page. See admin registration. -
Grouped filters.
Query.Filteris an optional boolean tree ANDed withWhereandAny, built withdb.Cond,db.And,db.Oranddb.Not(theExprandExprOptypes). AQuerywithout aFilterproduces exactly the SQL it did before. A filter holds at mostMaxFilterNodes(100) nodes andMaxFilterDepth(8) levels. -
IN,IS NULLandIS NOT NULL.OpInwithdb.In(field, slice)(a nil or empty list matches nothing on every dialect; at mostMaxInValues, 1,000, values per list andMaxQueryArgs, 10,000, bind values per query; a zerotime.Timeis rejected), andOpIsNull/OpIsNotNullwithdb.IsNull/db.IsNotNull, which take no value. All three work inWhere,AnyandFilter. A foreign key left at zero is stored asNULL, soOwnerID = 0still never matches (unchanged); useIsNullfor unset keys. -
Store.FirstandStore.Exists.Firstreads one row (primary-key order unlessOrderByis set,ErrNotFoundnaming the model when none, the destination untouched on any error);Existsreports whether any row matches. They validate and build SQL exactly asListandCountdo. -
Typed query errors.
ErrInvalidQuery,ErrQueryLimit,*QueryErrorand*QueryLimitError. Every malformed query is refused before any SQL runs. The existingWhere/Anyvalidation errors keep their text and now also matchErrInvalidQuery. -
Locale resolvers.
i18n.Resolver(a locale source that also names the request headers it depends on), the helpersFromQuery,FromCookieandFromHost,Chain(the host's order, thenAccept-Language),FuncResolverfor a plain function, andMiddlewareResolverto install one. Each helper returns only a locale with a registered catalog and none sets a cookie.MiddlewareandDefaultLocaleResolverare unchanged. -
i18n/i18ntest.Isolate. Test support:i18ntest.Isolate(t)gives a test an empty i18n state (catalogs, theOnMissinghook and its once-state, the observed keys) and restores the previous state int.Cleanup. A test that uses it must not be parallel. -
i18n.Keysandi18n.Validate.Trecords each (key, fallback) pair the first time it runs with a resolved locale (nothing is recorded, and nothing allocated, when no locale is set).Keys()lists them;Validate()checks every catalog against them and returns aReportwithProblems(ProblemMismatch,ProblemEmpty,ProblemConflictingFallbackwhen a key is seen with two fallbacks,ProblemRegistryFull) and the advisory, sortedUnobservedcatalog keys. It covers only what has run in this process, and the registry holds at most 4,096 keys, so fallbacks must be stable literals. -
i18n.OnMissing. A development hook that reports a missing translation (an absent key, an empty value or a value whose format verbs do not match the fallback's) with the resolved locale and key, at most once per pair. It isnilby default, runs outside the package's locks, andOnMissing(nil)clears it. -
The admin's remaining English is translatable.
<html lang>follows the selected catalog on every admin page and on the Markdown preview document (enwhen none is selected). The Markdown and JSON widgets' tab labels, buttons, character count,aria-labels, iframe title, script messages (Nothing to format.,Preview failed.and the rest, delivered asdata-msg-*attributes only when a locale was resolved), and the JSON validation errors now useadmin.*keys with the current English as fallback. An app without i18n renders the same output as before. A test keeps new literal text out of admin's templates. -
Translatable accounts pages. The register, login, password-reset and email-verification pages and their form errors (including the generic login error, which stays one message for every failure) go through
i18n.Tunderaccounts.*keys with the current English as fallback. A page declares<html lang>only when a catalog was selected, so an app without i18n renders exactly what it did before. The JSON API'serrortext stays English; clients branch oncode. -
Accounts emails in the request's language. The verification and reset emails are rendered in the locale of the request that queued them ( 8000
accounts.email.*keys, English fallback). The locale is captured when the email is queued, before any account lookup; the queued job keeps nothing else of the request. A translated body that lacks the%slink placeholder falls back to the English body, so the link is never dropped. -
The
tango newprojectscaffold points at the i18n guide. The generated middleware list carries a two-line comment saying how to opt in (i18n.Middleware(nil)and catalogs). The generated project is otherwise unchanged. -
examples/api-with-adminin Spanish. The example serves the admin in Spanish end to end: a completeescatalog, a smalles-MXoverride, a?lang=→ cookie →Accept-Languageorder and a language switcher, with a test that walks the pages in both locales and checksOnMissingandValidate. tanGO itself still ships no catalogs. -
examples/accounts-mailin Spanish. Registering, confirming an address and resetting a password run in Spanish, emails and links included, with a test that walks the flow and fails on any missing key.
Changed
-
The i18n middleware sets
VaryandContent-Language. Withi18n.Middleware(nil)every response getsVary: Accept-Language, so a cache in front of the app no longer serves one language to another visitor;MiddlewareResolver(Chain(...))sends the tokens its resolvers need (CookieforFromCookie).Content-Languagenames the selected catalog's locale, and only when a catalog was selected. ExistingVaryvalues, including ones a downstream handler adds, are merged without repeating a token (ignoring case). A resolver passed as a plain function adds noVary(useFuncResolverto declare one). Nothing changes for an app without the middleware. -
A bad catalog value falls back instead of printing garbage.
i18n.Tnow ignores a catalog value that is empty or whose format verbs differ from the fallback's (positional verbs such as%[2]scount, so reordering arguments is still fine), tries the base language, and then shows the fallback. Before,"Nuevo"for"New %s"renderedNuevo%!(EXTRA string=Pet)and an empty value rendered nothing. A literal%in a fallback must be%%once arguments are passed. -
Upgrade note: literal
%in i18n fallbacks. The fallback is a format string whenever arguments are passed, so a bare%is read as a format verb and must be escaped. Changei18n.T(ctx, "sale.label", "Save 10% on %s", item)toi18n.T(ctx, "sale.label", "Save 10%% on %s", item). Search the project'si18n.Tcalls and catalogs for%followed by a letter or space before relying on the new fallback rule.
Fixed
- Locale matching ignores case and the
-/_separator.Accept-Language: es-mx,ES-MXandes_MXnow select a catalog registered ases-MX(before,es-mxskipped the regional catalog andES-MXmatched nothing, not evenes). The locale the middleware stores is the catalog's own spelling, and catalogs registered under two spellings of one locale are merged.
v0.6.0
Added
-
Admin operational dashboard (opt-in).
admin.WithDashboard(admin.DashboardConfig{Status, Activity})turns/admin/into a page with database and migration status and recent request and job activity; without it, or with neither source set, the landing page is unchanged. The status comes from a function you supply (build it fromtango.Status), and the activity from anyobservability.Snapshotter. A failing or panicking source marks only its own card "unavailable" and logs the cause; the error text never reaches the page. New inobservability:SnapshotterandSnapshot(a read side that is separate fromRecorder),NewWindow(an opt-in in-memory collector: the last 60 minutes in one-minute buckets, HTTP requests by status class and latency, job runs by outcome, nothing per route or job, reset on restart, labelled "this instance only"), andMulti(feed several recorders at once). It is a starting point for "is this instance healthy right now", not a metrics store; keep an external monitoring system for history, alerts and several instances. -
MySQL 8.4 support.
mysql://user:pass@host:3306/dbinTANGO_DB_DSNselects the newdb.MySQLdialect, withgithub.com/go-sql-driver/mysqlas the driver. Migrations,Store, the admin,tango newproject --dialect=mysqlandtestdb(a fresh database per test;TANGO_TEST_DSN=mysql://…,testdb.MySQLOnly,testdb.NotMySQL) all work on it, and CI runs the suite on MySQL 8.4. Tables are InnoDB with theutf8mb4_bincollation; timestamps areDATETIME(6)in UTC; connections useREAD COMMITTEDunless the DSN sets another isolation level, and the default pool recycles a connection after five minutes. MariaDB is not supported. Differences to know: an unboundedstringthat isuniqueorindexed isVARCHAR(255)(a longer value returns a*db.ValueTooLongError),LIKEis case-sensitive, and a migration that fails part-way cannot roll back (the error names every applied step and writes no tracking row). See the setup guide. A project with ashell/main.gofrom before this release must copy the newdatabaseLabelfrom the shell guide before using MySQL, ortango shellprints the DSN's password. -
Admin dark mode. Every admin page now follows the browser's light or dark preference, and signed-in staff can pick Light, Dark or System from the sidebar footer; the choice is kept in a
tango_admin_themecookie scoped to/admin/. The light theme is nearly unchanged: input, checkbox and secondary-button borders are a shade darker, and primary and danger buttons darken on hover, so they meet WCAG contrast. Colours are now semantic tokens (bg-surface,text-ink,border-line, the status family, and so on) generated from one palette table, with contrast tests over its pairs in both themes. Widgets that hard-code light colours stay light, so switch them to the token classes in the admin guide; the Markdown preview stays a white canvas in both themes. There is nothing to configure.
Changed
-
AccessLoggeris free when its logger discards Info events. It used to wrap the response and build the event's attributes for every request and only then let the logger drop it (3 allocations a request). It now asks the logger first and calls the next handler directly. A logger that logs Info behaves as before; the level is read on every request, so aslog.LevelVarstill takes effect at once. -
Dependencies.
go.modnow requires chi 5.5.0 (was 5.3.2),golang.org/x/crypto0.58.0,x/sys0.49.0,x/term0.47.0 andmodernc.org/sqlite1.60.1, and addsgithub.com/go-sql-driver/mysql1.10.1 for the MySQL dialect. A project that depends on tanGO is raised to at least these versions the next time it updates; rungo mod tidy.
Documentation
- Choosing
MaxOpen. The configuration guide now explains how the size of the database pool shapes tail latency, with measured figures, and suggests starting near the database's CPU count.
v0.5.0
Added
- OpenAPI documents.
openapi.New(openapi.Options{...})inInstalledAppsserves an OpenAPI 3.1 document of every included route at/openapi.json(opt-in: nothing is served otherwise).openapi.Devis the same app served only whenTANGO_OPENAPI=1, so a deployed process exposes nothing unless it sets the variable. Each route is listed with its method, path, path parameters, name and a tag from its prefix.tango.Doc(tango.RouteDoc{...})adds a summary, a request body, query parameters, responses and a bearer requirement, with schemas reflected from Go types (encoding/jsontags, nested and recursive types,varchar=nasmaxLength); a type can name its schema withSchemaName().tango checkfails and names a route whose documented types cannot be described. TheaccountsJSON endpoints document themselves; the admin's pages and the cookie-flow pages are hidden from the document.RouteRegistry.Describedandtango.DescribedRouteexpose the route table to tools.tango newprojectnow leaves a comment inproject/project.gosaying where to add it. See OpenAPI documentation. tango openapi [-o file]prints or writes the document (the new-tango-openapiapp-side flag, handled byDispatchFlags;DumpOpenAPI,OpenAPIProviderandErrNoOpenAPI). The output is the same bytes on every run, and a failed run leaves an existing file untouched.- Swagger UI.
openapi.Options{UI: swaggerui.New()}adds a browsable page at/docs/from Swagger UI 5.17.14 embedded in the binary (Apache-2.0; no network request). It is the separate packageopenapi/swaggeruiand adds about 1.7 MB to a binary that imports it.
Changed
-
Database connections are reused under load.
database/sqlkeeps only 2 idle connections, so a server handling more than 2 requests at once closed and reopened a database connection on almost every request (measured: about 10,900 PostgreSQL sessions opened in one 15-second run of single-pet reads).ServeContextnow raises the idle limit to 32 unless your app bounded the pool withSetMaxOpenConns.tango.WithDBPool(tango.DBPool{...})sets the limits explicitly;tango.WithDBPool(tango.DBPool{})restores the previous behavior. The number of open connections is unchanged (unlimited). -
Foreign keys are not indexed unless you say so (guidance). A
fk=column is not indexed by itself, so filtering or joining on it scans the table (measured:liston a 10,000-row table ran at about 1,300 requests a second without the index and about 3,200 with it). Writetango:"fk=Category,index"on foreign keys you filter or join on. Indexing foreign keys by default, as Django does, is planned for a later minor release; this entry is the notice.
Fixed
- The admin no longer comes up silently empty. The admin builds its pages when it is installed, so a model registered by an app listed after
admin.Newnever appeared in it.tango check(and-check) now fails and names those models, thetango newprojectscaffold says to add apps aboveadmin.New, andtango newapprepeats it when the project installs the admin. Moveadmin.Newafter your apps.
v0.4.0
Added
-
JSON fields.
tango:"json"on astringfield declares it holds JSON text (model.FieldMeta.JSON).Store.CreateandStore.Updaterefuse text that is not valid JSON with a*db.InvalidJSONErrorthat matchesdb.ErrInvalidJSONand never contains the submitted text; the empty string is unset,nullis valid, and the stored text is exactly what was given. It is ordinaryTEXTon SQLite and PostgreSQL, so adding the tag to an existing field generates no migration and does not scan existing rows; reads are not checked.jsoncannot be combined withvarchar=n,text,pk,fk,uniqueorindex. See ADR 0059. -
JSON fields in the admin. A
tango:"json"field getsadmin.JSON()by default (Edit and Formatted tabs) with noOptions.Widgetsentry; an explicit entry still wins, and read-only and changelist rendering are unchanged. A save the store refuses for invalid JSON, including through a non-JSON widget such asadmin.Textarea(), re-renders with a 422 and a translatable field error (admin.error.invalid_json, "Not valid JSON.") beside the field, keeping the text as typed. See admin registration. -
Admin refinement.
admin.JSON()edits a string field as JSON (syntax checked on save, the submitted text stored exactly, a browser-side Formatted tab).admin.Markdown(...)edits Markdown in a monospace textarea with a character count and, when you passadmin.WithMarkdownPreview, a sandboxed Preview tab from your own renderer: tanGO ships no parser or sanitizer, and you decide how HTML is sanitized (ADR 0058).Options.Filtersadds boolean and foreign-key filters to the changelist (they combine with search and ordering; an over-large foreign-key filter still applies a primary key given in the URL).Options.Displaywithadmin.DisplayFuncandadmin.Displayrenders computed changelist cells, such as a file's size and an authorized download link, without admin knowing about storage;admin.ByteSizeandadmin.ShortHashhelp.admin.FieldErrorlets a widget report an error beside its own field. Forms now renderHelpTextand mark invalid fields witharia-invalidandaria-describedby; the changelist gets a labelled search box and filters, a caption and column scopes.Options.Labelsnow also names a field's changelist column when set. See admin registration and ADRs 0057 and 0058. -
Bounded strings.
tango:"varchar=n"declares astringfield of at mostncharacters (1 to 10,485,760), andtango:"text"states an unbounded one explicitly; a barestringstays unbounded text and generates no migration.model.FieldMeta.MaxLengthcarries the limit and a malformed tag failsRegisterwithmodel.ErrInvalidFieldTag.Store.CreateandStore.Updaterefuse a longer value before any SQL with a*db.ValueTooLongError(db.ErrValueTooLong), counting runes the way PostgreSQL counts characters; SQLite does not enforce the length and raw SQL is not checked.tango makemigrationswrites aVARCHAR(n)column (Column.Length, additive, with noCHECK), generates the widening changes (varchar(n)totextor a largervarchar) and the narrowing ones (texttovarchar(n)or a smallervarchar), and a narrowing checks the existing data in Go first, failing with the number of rows and one offending key instead of truncating anything. A migration of narrowings is reversible; a widening makes its migration irreversible. The admin rendersmaxlengthand shows a translatable per-field message (admin.error.too_long) for a refused save, andadmin.FieldContextgainsMaxLength. Built-in models are not retagged. See models and tags and changing a field's type. -
Accounts for a single-page app.
accounts.WithJSONmounts six bearer-only JSON endpoints under/accounts/api/(register, login, password reset request and confirm, verify, resend verification) for a separate client, sharing the HTML flow's rules, limiters and outbox. The host supplies the token side throughaccounts.JSONAuth(Issue,Authenticate) andAuthGrant, soaccountsimports no token package; JSON mode never reads or sets a cookie and has no logout.JSONConfigalso takes the emailed link templatesVerifyURLandResetURL({token}once; prefer a fragment), anOnRegisterhook that runs inside the account's transaction with aRegistration(aFieldErroror*db.ValueTooLongErroranswers422), andResolveIdentifierso login can take a username. Requests are strict (415,413,400 invalid_body), errors are{"error", "code", "fields"?}, and every response isno-store. Newdb.Store.InTxruns a callback in one transaction (commit, rollback on error, rollback and re-panic on panic; nested calls join). See the accounts guide, the newexamples/spa-accountsand ADRs 0050 and 0051. -
Accounts answers invalid JSON as a field error. In the JSON accounts API, a
*db.InvalidJSONErrorfrom a registration hook'stx.Create(alone or joined witherrors.Join) answers422 invalid_field, keyed by the Go field name with the messagemust be valid JSON, instead of a generic500; the document is never echoed. See the accounts guide. -
File uploads and storage. The new
storagepackage is an explicit object store for uploaded files, used from ordinary Views:Putstreams a file in, always sniffs its content type, enforces a required size cap and an optional allowed-types list, and returns a generated opaque key with the size and SHA-256;Stat,Open(a byte range) andDeletecomplete theStore. There is noFileField, no file model, no listing and no signed URLs: the host keeps the key and metadata in its own model and authorizes every access.storage.Uploadreads one multipart file with bounded memory, andstorage.Servedelivers an authorized object with ranges, conditional requests, attachment by default andnosniff. Backends:storage/local(atomic,os.Root-contained, for development and one host),storage/s3(Amazon S3, Cloudflare R2 and other S3-compatible providers, in its own Go module so no cloud SDK reaches yourgo.mod), andstoragetestwith an in-memoryStoreand the conformance suite everyStorepasses. See the uploads guide, the newexamples/uploadsand ADRs 0052 to 0054. Native Google Cloud Storage is a later release. -
Caching. The new
cachepackage is a small, explicit cache for recomputable reads: a bytes-onlycache.Store(Get,Setwith a TTL of up to 30 days,Delete) where a miss is not an error, one portable key rule,cache.Prefixfor namespaces and bulk invalidation by version, typed JSON helpers (GetJSON,SetJSON,ErrCorrupt), and the fail-openFetchJSONread-through that reports cache failures to anOnErrorhook and never fails the request because the cache is down.cache/localis a bounded in-process store (entry limit, optional byte budget, least-recently-used eviction);cache/redis(Redis and Valkey) andcache/memcacheare their own Go modules, so no client library reaches yourgo.mod.cachetest.Runis the conformance suite every backend passes. There is no response, fragment or ORM caching, no automatic invalidation, and nothing logs. See the caching guide, the newexamples/cacheand ADRs 0055 and 0056.
Changed
-
An admin changelist
?page=beyond the last page now shows the last page, so the rows and the pager always describe the same page (before, it showed an empty list under a pager that named the last page). -
The admin foreign key select now starts with a "— None —" choice (translation key
admin.fk.none), and an unset foreign key shows an em dash in the changelist instead of0. Saving "None" stores the same unset value (NULL) as before. -
POST /admin/logout/now requires the session's CSRF token when the request carries a session cookie, so a cross-site form cannot sign an admin out. A missing or wrong token gets 403 and leaves the session in place. A request without a session cookie still redirects to the login page. -
The admin sidebar footer no longer says "Signed in over Basic Auth" (admin has used session logins since 0.3). It now shows "Signed in as " with a Log out button that posts to
/admin/logout/with the session's CSRF token. The translation keyadmin.layout.signed_inis replaced byadmin.layout.signed_in_asandadmin.layout.logout. -
/accounts/login/now always spends one password comparison, even for an unknown or inactive account, so its timing no longer says whether an account exists. Nothing else about the HTML flow changes.
v0.3.1
Fixed
db.Querywith anOffsetand noLimitfailed on SQLite with a SQL syntax error (SQLite refusesOFFSETwithoutLIMIT).Listnow skips the rows and returns the rest on both dialects. It also madetango shell'sList(model, map[string]any{"offset": n})fail the same way.
v0.3.0
Added
tango shell: a Go prompt on your project's models and database, with nothing served. It is a Yaegi interpreter (pinned at v0.16.1) run by the project's ownshell/main.gothrough the newshellpackage, so the server never links it. HelpersModels,Describe,Get,List,Count,Create,UpdateandDeletework on any registered model addressed asapp.Model, with plain-map queries and rows;-c EXPRand piped input make it scriptable;--readonlyrefuses writes;Options.Helpersadds your own functions asproject.Name. At a terminal it has line editing, per-project history under your cache directory (TANGO_SHELL_HISTORY=offdisables it), and Ctrl-C that clears the line, or ends a running evaluation with status 130. It says what Go the interpreter cannot run (min,max,clear, some generics, ranging over a function or an integer) and keeps the session through errors and panics. It runs your code with your project's credentials; it is not a sandbox. See the shell guide, ADR 0048 and ADR 0005. Addsgithub.com/traefik/yaegito the root module; only a binary that importsshelllinks it.admin.WithTrustedProxiesandaccounts.WithTrustedProxies: behind a reverse proxy, the failed-attempt limiters count the client address your proxy saw (the rightmostX-Forwarded-Forentry outside the networks you name) instead of the proxy's own, so users no longer share one bucket. Opt-in: without it nothing is read fromX-Forwarded-Forand behaviour is unchanged, and only requests from the named networks may supply a forwarded address. The limiter also no longer keeps an entry for an address that has no recent failure. See behind a reverse proxy.- Running more than one instance: what is shared across instances (sessions, accounts, tokens), what is per process (the login limiter,
ratelimit,realtimerooms, theaccountsmail outbox and cooldown) and the workarounds, with ADR 0047 recording that shared state is not built yet and what would reopen it. No API changes. - A
tango tuiguide, with screens checked against the code by a test, and the promise about the dashboard in versioning and compatibility: the command, its terminal requirement, confirmation before database changes and delegation to the supported operations are covered; layout, wording and key bindings are not.
Changed
tango newprojectwrites two more directories.project/project.goholdsfunc Config(store *db.Store) tango.Config: the installed apps, middleware and ordinary configuration thatmain.goused to build inline, so the server and the shell register the same apps from one list.main.goopens the database, builds the store and callsproject.Config(store).shell/main.gois the programtango shellruns.tango newappnow says to install a new app inproject/project.gowhen that file exists. Existing projects keep working as servers; to get a shell they follow the documented upgrade, a diff tested against the scaffold as it was before (ADR 0048).- The tutorial and the
examples/boardproject list their apps inproject/project.go; the board's token service and live feed are built insideproject.Config, which stops the process with their error message when they cannot start. tango admin createandtango admin resetpassworduseTANGO_ADMIN_PASSWORDwhen it is set and non-empty, with no prompt. It was documented but never read. The value is never printed; the command names the variable instead.tango migratesays what it did:applied 2 migrations: admin/0001_auto_…, blog/0002_auto_…, orno pending migrations, instead of always printingmigrations applied. A project gets the new wording when it is built against this version; the rollback line is unchanged.tango newprojectends with the real first-run order (tango makemigrations,tango migrate,tango admin create <username>), and the generated project printsadmin: http://localhost:8000/admin/afterlistening on(not with--no-admin). Existing projects are unchanged.tango tui:- the greyed-out "Shell" item is gone;
- "Apply pending migrations" and "Roll back the latest migration" grey out with a reason when status shows they cannot run (nothing to apply, nothing to roll back, or project status incomplete);
- the confirmation prompts say what they will do.
Security
ratelimit.RemoteIPKey(trustedProxies...)could be made to give a client the key it chose. It took the leftmostX-Forwarded-Forentry, which the client writes when the proxy appends to the header (nginx's default), and it did not check that the value was an IP address, so a client behind a trusted proxy could rotate its key to evade a limit or flood the limiter with new keys. It also fell back toX-Real-IP. It now readsX-Forwarded-Foronly from a trusted peer, parses every entry as an IP address, walks the list from the right skipping trusted proxies, and takes the first other address, which is the one your nearest trusted proxy saw.X-Real-IPis ignored, and a valid address is returned in canonical form. Unusable data falls back to the peer's address. The failed-login limiters ofadminandaccounts(admin.WithTrustedProxies,accounts.WithTrustedProxies) use the same resolver. This changes behaviour under the compatibility promise's security exception.- Upgrade: nothing changes without trusted proxies. With them, check that your proxy adds the address it sees to
X-Forwarded-For(appending and replacing both work; passing the header through untouched does not). If you relied onX-Real-IP, make the proxy put the client address inX-Forwarded-For. Keys for IPv6 clients are now lower-case and compressed, and IPv4-mapped IPv6 addresses are keyed as IPv4, so a limit that was counted under the old spelling restarts once.
- Upgrade: nothing changes without trusted proxies. With them, check that your proxy adds the address it sees to
Fixed
tango admin createandresetpasswordno longer show the password as you type it on a terminal. Piped input is read as before. This addsgolang.org/x/termto the root module (ADR 0046).- Ctrl-C leaves
tango tuieven while a confirmation is showing; it used to be ignored until you answered. - Projects created by
tango newprojectnow shut down gracefully: the generatedmain.gocallstango.ServeContextundersignal.NotifyContextfor Ctrl-C andSIGTERM, so in-flight requests finish and registeredLifecyclecomponents stop. It calledtango.Serve, which never reacts to a signal. Existing applications are unchanged; swap inServeContextas the application lifecycle guide shows. tango tuino longer ends the session when an apply or rollback fails. It showsLast action failed: …with the exit code and the command's last error line, refreshes the status, and returns to the menu; if the refresh also fails, both errors show.- Stopping the server started from
tango tuiwith Ctrl-C orSIGTERMis a clean stop: tango waits for the server, printsserver stoppedand exits 0. It used to die with the signal. A server that fails, or exits with no signal, keeps its exit code. tango tuiexplains a status failure (runtango check; an oldermain.gomay needtango.DispatchFlags) before the raw error, which is kept.