ShapeShifter is a Go middleware library that adapts JSON HTTP contracts at the edge of your application. Controllers keep reading and writing one canonical internal JSON shape, while ShapeShifter maps external request and response contracts around them.
external request -> ShapeShifter -> internal controller request
internal response -> ShapeShifter -> external response
Current capabilities:
- Core transform engine with request and response pipelines
- Runtime catalog with pluggable storage and atomic publish of transformation changes
- YAML runtime config for one-time framework settings such as catalog source, limits, and UI options
- Legacy YAML/JSON static spec loader with load-time schema, jq, path, handler, and contract validation
- JSON Schema 2020-12 validation through
github.com/santhosh-tekuri/jsonschema/v5 - jq source expressions through
github.com/itchyny/gojq - Echo adapter, preview API, and example app
- Gin adapter
- Route-scoped Chi adapter
- Fiber adapter
- Embedded static contract portal for docs, examples, previews, version comparison, catalog editing, and opt-in same-origin try-it-out
- No-op-by-default observer hook with a simple
ObserverFunchelper
go get github.com/standard-librarian/shapeshifterregistry := shapeshifter.NewRegistry()
cfg, err := shapeshifter.LoadConfigFile("shapeshifter.yaml")
if err != nil {
return err
}
catalogPath := cfg.Catalog.Params["file"]
if catalogPath == "" {
catalogPath = "catalog.yaml"
}
catalog, err := shapeshifter.LoadCatalogFile(catalogPath)
if err != nil {
return err
}
runtime, err := shapeshifter.NewRuntime(
context.Background(),
shapeshifter.NewMemoryCatalogStore(catalog),
registry.Snapshot(),
)
if err != nil {
return err
}
e := echo.New()
e.Use(shapeshifterecho.Middleware(runtime.Engine()))
shapeshifterecho.MountRuntimeAPI(e, runtime)
e.POST("/users", createUser)The selected contract is endpoint-scoped. A v2 contract on POST /users is independent from a v2 contract on another route.
Run the Echo example:
cd examples/echo-example
go run .Default v1 request:
curl -X POST http://localhost:8080/users \
-H 'Content-Type: application/json' \
-d '{"name":"Alice","email":"[email protected]"}'Explicit v2 request:
curl -X POST http://localhost:8080/users \
-H 'Content-Type: application/json' \
-H 'X-ShapeShifter-Contract: v2' \
-d '{"full_name":"Alice","contact":{"email":"[email protected]"}}'The controller sees this internal request in both cases:
{"name":"Alice","email":"[email protected]"}For v2, the client receives:
{"id":"123","full_name":"Alice","contact":{"email":"[email protected]"}}Echo can mount runtime preview and catalog endpoints for local tooling or an authenticated internal console:
shapeshifterecho.MountRuntimeAPI(e, runtime)Default routes:
GET /_shapeshifter/api/specGET /_shapeshifter/api/catalogPUT /_shapeshifter/api/catalogPOST /_shapeshifter/api/catalog/validatePOST /_shapeshifter/api/process/requestPOST /_shapeshifter/api/process/response
Preview request transform:
curl -X POST http://localhost:8080/_shapeshifter/api/process/request \
-H 'Content-Type: application/json' \
-d '{"route":{"method":"POST","path":"/users"},"contract":"v2","body":{"full_name":"Alice","contact":{"email":"[email protected]"}}}'Preview response transform:
curl -X POST http://localhost:8080/_shapeshifter/api/process/response \
-H 'Content-Type: application/json' \
-d '{"route":{"method":"POST","path":"/users"},"contract":"v2","body":{"internal_id":"123","name":"Alice","email":"[email protected]"}}'Preview processing uses ModePreview. Handlers registered without PreviewSafe: true are skipped and returned in skipped_handlers.
Detailed API docs:
- Spec v1
- Config v2
- Catalog v2
- HTTP APIs
- Error model
- Public API surface
- Release and stability
- v0.1.0 release notes
- v0.2.0 release notes
The embedded UI is a static, dependency-free contract portal. It uses the preview API to document loaded contracts, render schema-driven examples, preview both transform directions, compare versions, and manage browser-local fixtures.
shapeshifterecho.MountRuntimeAPI(e, runtime)
uiHandler := http.StripPrefix(
"/_shapeshifter/ui",
ui.Handler(
ui.WithPreviewAPIBase("/_shapeshifter/api"),
ui.WithTryItOut(true),
ui.WithEditing(true),
ui.WithTryItOutBase("/"),
),
)
e.GET("/_shapeshifter/ui", func(c echo.Context) error {
return c.Redirect(http.StatusFound, "/_shapeshifter/ui/")
})
e.GET("/_shapeshifter/ui/*", echo.WrapHandler(uiHandler))Open:
http://localhost:8080/_shapeshifter/ui/
ui.Handler() is backwards compatible and accepts options:
ui.WithPreviewAPIBase(path)sets the preview API base. Default:/_shapeshifter/api.ui.WithTryItOut(true)enables the real request tab. Default: disabled.ui.WithTryItOutBase(path)sets the same-origin base path for real execution. Default:/.
The handler also serves GET /config.json, so a UI mounted at /_shapeshifter/ui fetches /_shapeshifter/ui/config.json.
The portal is designed for backend and frontend engineers:
- FE can discover endpoints, contract versions, schemas, headers, curated examples, and expected responses.
- BE can preview
external request -> internal requestandinternal response -> external response. - Both teams can compare two contract versions on one endpoint.
- Examples saved in the UI use browser
localStorageundershapeshifter.examples.v1; ShapeShifter does not persist them server-side. - Try-it-out sends real same-origin HTTP requests only when explicitly enabled and never runs automatically.
- Editing sends catalog writes to the runtime API only when explicitly enabled and mounted by the host application.
Security notes:
- Do not expose preview or UI routes publicly without application-owned auth.
- Do not expose catalog write routes publicly without application-owned auth. ShapeShifter does not provide auth middleware.
- Try-it-out can mutate application data because it calls real handlers.
- Preview mode skips handlers that are not registered with
PreviewSafe: true; skipped handler names are shown in the response. - ShapeShifter does not provide auth middleware for the portal.
Handlers run after field mapping and coercion. They may mutate and return the target map.
registry := shapeshifter.NewRegistry()
err := registry.Register("normalizeUserInput", func(input map[string]any) (map[string]any, error) {
if name, ok := input["name"].(string); ok {
input["name"] = strings.TrimSpace(name)
}
return input, nil
}, shapeshifter.HandlerOptions{PreviewSafe: true})Runtime catalog compilation takes registry.Snapshot(), so handlers registered after runtime creation do not affect already compiled catalog revisions.
ShapeShifter does not log directly. Use an observer to connect it to your logger, metrics, or tracing backend.
observer := shapeshifter.ObserverFunc(func(event shapeshifter.Event) {
slog.Info("shapeshifter",
"kind", event.Kind,
"route", event.Route,
"contract", event.ContractID,
"phase", event.Phase,
"stage", event.Stage,
"duration", event.Duration,
"in_bytes", event.InBytes,
"out_bytes", event.OutBytes,
"reason", event.Reason,
)
})
engine, err := shapeshifter.NewEngine(spec, shapeshifter.WithObserver(observer))The Echo example includes a concrete observer that logs selected contracts, bypasses, transform success, validation failures, and handler failures.
Echo uses c.Path():
e := echo.New()
e.Use(shapeshifterecho.Middleware(engine))Gin uses c.FullPath():
r := gin.New()
r.Use(shapeshiftergin.Middleware(engine))Chi is route-scoped because Chi does not reliably expose the route pattern early enough for global request-body transformation:
r.With(shapeshifterchi.Route(engine, "/users/{id}")).Post("/users/{id}", handler)Fiber uses c.Route().Path. Mount it in the route handler chain so the matched route path is available before request transformation:
app.Post("/users/:id", shapeshifterfiber.Middleware(engine), handler)Adapter notes:
In v0.2.0, shapeshifter.yaml is runtime/framework config. Transformations live in a version: "2" catalog loaded through a CatalogStore.
- The built-in stores are
NewMemoryCatalogStoreandNewFileCatalogStore. - Production applications can provide their own
CatalogStore. - Runtime catalog saves validate and compile before publishing.
- Failed saves leave the previous live catalog active.
expected_revisionprotects catalog writes from stale editor sessions.
The legacy LoadSpecFile API still accepts static version: "1" transformation specs for existing users, but the v0.2.0 path is runtime config plus catalog store.
versionis required and must be"1".- Optional top-level
titleanddescriptionare preserved for documentation. - Optional endpoint
summary,description, andtagsare preserved for documentation. - Optional contract
summary,description, anddeprecatedare preserved for documentation. - Optional request/response examples are validated at load time against their external schemas and exposed through the sanitized spec.
methodis normalized to uppercase.pathis the adapter-native route pattern.- Duplicate
method + pathendpoints are rejected. - Duplicate contract IDs within one endpoint are rejected.
- Missing contract headers use
default_contractonly when it is explicitly configured. - Unknown contract headers return
400. - JSON Schema
$refis rejected in this version. - Request passthrough requires root
additionalProperties: false. - Response passthrough is not supported; responses must use explicit
fields. - Target paths support object paths like
.contact.email. - jq programs are trusted spec configuration and are compiled at load time.
gojq.RunWithContextcancellation is available; default runtime guardrails enforce output-count and emitted-value-size limits.- The sanitized preview spec includes JSON Schemas and handler metadata, but not handler functions or compiled internals.
Request side:
- Missing or unknown contract:
400 - Invalid request
Content-Type:400 - Malformed JSON, empty body, root array, or scalar root:
400 - Request body above limit:
413 - Valid JSON that fails schema, validation, mapping, coercion, or handler validation:
422 - Ordinary request handler system failure:
500
Response side:
- Only buffered JSON responses are transformed.
HEAD,204,304,>=400, non-JSON content types, and non-identity content encodings bypass transformation.- Response validation, transform, handler, target validation, marshal, or response-size failures return a controlled
500JSON envelope. - On response transform failure, stale content headers are cleared and only safe correlation headers are preserved.
Defaults:
const (
DefaultRequestBodyBytes int64 = 65536
DefaultResponseBodyBytes int64 = 1048576
)Endpoint limits override top-level limits. Zero and negative limits are invalid.
go test ./...
go test -race ./...
go vet ./...The suite covers loader validation, transform semantics, JSON eligibility, request and response limits, real HTTP server behavior, preview processing, observer delivery, adapter behavior, concurrency, conformance fixtures, and fuzz seeds for paths and number normalization.
The language-neutral conformance fixtures live in conformance. They define shared expected behavior for request/response transforms, selection errors, validation errors, coercion, jq output limits, and preview handler behavior.
- Streaming responses, SSE, websockets, and hijacked connections
- Multipart/file upload transformation
- Root arrays or scalar JSON roots
- Cross-framework route pattern normalization
- Independent request-contract and response-contract selectors
- Arbitrary jq mutation/update programs
- Response passthrough