Mirra folds several providers' safety refusals into one sentinel, bounds response decoding, and keeps UI state in enum-indexed arrays.
· 7 min read

How Mirra Normalizes Image API Errors in Go


OpenAI calls it moderation_blocked. Azure calls it content_filter. Ark says SensitiveContentDetected. DashScope says DataInspectionFailed. Mirra collapses these provider-specific refusals into a single sentinel so the rest of the app can use errors.Is(err, errBlocked).

Mirra (镜衣) is an NSGo app in Go. It picks a face, an outfit and a pose from three public reference galleries and hands them to an image model, in the cloud or on your own machine. For a Go developer, the interesting part is how apps/mirra normalizes several providers’ different response shapes before errors reach the UI.

Making every provider’s refusal match one error

apps/mirra/apis.go defines a statusError for failed HTTP answers, and then does something you don’t see often:

// Is makes a refusal by the service's safety system match errBlocked.
func (e *statusError) Is(target error) bool {
	return target == errBlocked && isBlocked(e.Type, e.Message)
}

errors.Is calls an error’s Is(error) bool method as it traverses an error tree, so a concrete error type can decide at runtime which sentinel it matches. The same *statusError value may or may not match errBlocked, depending on the Type and Message the provider sent back.

isBlocked checks substrings in both the machine-readable code and the human message:

func isBlocked(code, message string) bool {
	code, message = strings.ToLower(code), strings.ToLower(message)
	for _, c := range []string{"moderation", "content_policy", "content_filter", "sensitive", "safety", "responsibleai", "datainspection"} {
		if strings.Contains(code, c) {
			return true
		}
	}
	for _, m := range []string{"safety system", "content policy", "content filter", "moderation", "sensitive content", "inappropriate content", "data inspection failed"} {
		if strings.Contains(message, m) {
			return true
		}
	}
	return false
}

Substring matching on error prose is fragile. Here the classification only selects the message shown to the user. A missed match falls through to the generic HTTP-status explanation; it does not trigger a retry or another operation. That is a much narrower risk than parsing prose to drive control flow.

Mirra also handles refusals inside successful responses, including Gemini finish reasons and Ark per-image errors. A second type carries that reason while matching the same sentinel:

type blockedError struct{ Reason string }

func (e *blockedError) Error() string        { return errBlocked.Error() + ": " + e.Reason }
func (e *blockedError) Is(target error) bool { return target == errBlocked }

Two unrelated types, one sentinel. Callers never learn which provider produced the failure.

Ordering matters when a type can match two things

apps/mirra/errors.go turns errors into user-facing text with a switch over errors.Is and errors.As:

case errors.Is(err, errBlocked):
	var blocked *blockedError
	detail := ""
	if errors.As(err, &status) {
		detail = or(status.Message, status.Status)
	} else if errors.As(err, &blocked) {
		detail = blocked.Reason
	}
	return withDetail(t.ErrBlocked(), detail)
case errors.As(err, &status):
	detail := status.Message
	...

Since *statusError can match errBlocked, the errors.Is case has to come first. If the errors.As case for *statusError came first, refusals represented by that type would render as ordinary HTTP failures. A custom Is method widens what the type matches, so the order of this switch is part of its behaviour even though the compiler cannot enforce it.

Inside the blocked branch the code still uses errors.As to recover the concrete type and pull a detail line out of it: Is selects the category, while As retrieves the payload.

The same function groups context.DeadlineExceeded with a net.Error whose Timeout() method returns true. A plain context.Canceled does not match this branch.

Bounding reads on responses you didn’t write

Image APIs return pictures inline as base64, so responses are large by design. postJSON still won’t decode an unbounded body:

if resp.StatusCode/100 != 2 {
	return apiError(resp)
}
if err := json.NewDecoder(io.LimitReader(resp.Body, 4*maxImageBytes)).Decode(out); err != nil {
	return fmt.Errorf("image API: %w", err)
}

The error path gets a far tighter ceiling, io.ReadAll(io.LimitReader(resp.Body, 64<<10)), because an error response is expected to contain only a small status payload. Separate limits avoid making image responses too small or error responses needlessly large.

postJSON builds its request with http.NewRequestWithContext, sets Content-Type, applies a map[string]string of per-provider headers, and closes the body with defer. The signature takes body, out any and handles marshal and unmarshal internally, so each provider’s call site shrinks to a struct literal and a decode target.

Embedded backgrounds behind a fake URI scheme

An Item has one Full field, but a reference picture can come from a remote gallery URL, a file the app saved, or an asset compiled into the binary. apps/mirra/backgrounds.go handles the third case with a scheme prefix rather than extra fields:

//go:embed backgrounds/*.jpg
var backgroundFiles embed.FS

const backgroundScheme = "background:"

Group metadata lives in the filename. backgroundCatalog reads the embedded directory and matches each entry against a group prefix, so indoor-brick-wall.jpg lands in the indoor group without a manifest file that someone has to remember to update:

entries, _ := backgroundFiles.ReadDir("backgrounds") // the directory is embedded, so it reads

Dropping that error is fine here, and only here: the directory is baked in at compile time, and a //go:embed pattern matching nothing fails the build.

Resolving a URI back to bytes is short, but the path.Base call is important:

func backgroundData(uri string) ([]byte, bool) {
	name, ok := strings.CutPrefix(uri, backgroundScheme)
	if !ok {
		return nil, false
	}
	data, err := backgroundFiles.ReadFile("backgrounds/" + path.Base(name))
	return data, err == nil
}

strings.CutPrefix tests and trims the scheme in one call. path.Base strips directory components before the name is joined to the embedded directory. The embedded filesystem is read-only and rooted in the compiled assets, but canonicalizing the name still keeps the lookup contract clear.

Enum kinds as array indices

apps/mirra/gallery.go declares the reference types with a count sentinel:

const (
	KindPose Kind = iota
	KindCostume
	KindFace
	KindBackground
	// kindCount is how many kinds there are, the length of the studio's arrays by kind.
	kindCount
)

app.go keys state off it with fixed-size arrays instead of maps:

chosen [kindCount]*core.Signal[*Item]
filter [kindCount]*core.Signal[string]
adult  [kindCount]*core.Signal[bool]

The arrays themselves need no map allocation, and lookups have no missing-key case. Add a Kind above kindCount and the array lengths change at compile time.

The cost is real though. Enum values become part of your storage layout, so reordering the constants changes which index means what. For in-memory UI state that’s a non-issue. The moment any of this gets serialized by number, it’s a landmine.

One App struct, injectable at the edges

Everything the app reaches outside itself lives in one struct, and the doc comment says why:

// App is the app with what it reaches outside: tests give it local servers and a temporary directory.
type App struct {
	Client *http.Client
	Sites  Sites
	// DataDir keeps works and uploads; the app's data directory when empty.
	DataDir string
	// Pictures keeps them; files, or memory in a browser, when nil.
	Pictures pictures
}

Sites holds the three gallery origins. DefaultSites points at the public ones, and the type’s comment marks them overridable in tests. main builds the struct and hands it over:

app := App{Client: &http.Client{Timeout: 5 * time.Minute}, Sites: DefaultSites}
nsgo.Run(app.Root, nsgo.WindowSize(1280, 860))

Zero values carry weight here. An empty DataDir means the platform default; a nil Pictures selects files on native platforms or an in-memory store in a WebAssembly build. Tests can replace either dependency with a struct literal, while production stays a one-liner.

Signals, not re-renders

UI state is reactive, and desktop.go passes signal methods as function values straight into widgets:

ui.Tabs[int]{Label: t.TabsLabel(), Options: sections, Value: s.section.Get, OnChange: s.section.Set, TestID: "sections"}

Value wants a func() int, OnChange a func(int), and the core.Signal[int] methods satisfy both without a closure wrapper. The section body sits inside core.Dynamic(func(cx *core.Scope) core.Node { ... }), scoping the rebuild to that subtree rather than the whole tree. Styles follow the same pattern: where a style depends on theme colors or signal state, it’s a StyleFunc rather than a static Style.

Two smaller details. Interactive nodes carry a TestID, which turns UI assertions into string lookups instead of tree walks. And the phone/desktop split is one constant:

// wideWidth is the window width, in points, from which the app shows the desktop studio instead of the phone's tabs.
const wideWidth = 900

One shared studio state struct feeds two layout functions. studio embeds App and adds a cancel context.CancelFunc next to a busy signal, so a running generation can be cancelled from the UI, with the five-minute client timeout as a backstop.

Provider keys follow the same dependency-boundary approach. Mirra stores them through NSGo’s core.Secrets; when no secure store exists, as in the web build, it keeps them only for the page’s lifetime instead of falling back to plain storage. For a concrete look at native keychain access from Go, see how GoVault reaches the macOS Keychain without cgo.