Skip to main content

Overview

The transformer middleware transforms request and response data, enabling format conversion, field mapping, and data manipulation. Use it when you need:
  • API version compatibility
  • Field renaming/mapping
  • Format conversion

Installation

import "github.com/go-mizu/mizu/middlewares/transformer"

Quick Start

app := mizu.New()

// Transform request JSON
app.Use(transformer.Request(func(data map[string]any) map[string]any {
    // Rename field
    data["user_name"] = data["username"]
    delete(data, "username")
    return data
}))

Configuration

Options

OptionTypeDescription
Requestfunc(map[string]any) map[string]anyTransform request
Responsefunc(map[string]any) map[string]anyTransform response

Examples

Request Transformation

app.Use(transformer.Request(func(data map[string]any) map[string]any {
    // Snake case to camel case
    if v, ok := data["first_name"]; ok {
        data["firstName"] = v
        delete(data, "first_name")
    }
    return data
}))

Response Transformation

app.Use(transformer.Response(func(data map[string]any) map[string]any {
    // Add metadata
    return map[string]any{
        "data":    data,
        "version": "2.0",
    }
}))

Field Mapping

fieldMap := map[string]string{
    "userName": "username",
    "firstName": "first_name",
    "lastName": "last_name",
}

app.Use(transformer.WithFieldMap(fieldMap))

Version Compatibility

// v1 to v2 transformation
app.Use(transformer.Request(func(data map[string]any) map[string]any {
    // v1 had "name", v2 expects "fullName"
    if name, ok := data["name"]; ok {
        data["fullName"] = name
        delete(data, "name")
    }
    return data
}))

API Reference

Functions

// Request creates request transformer
func Request(fn func(map[string]any) map[string]any) mizu.Middleware

// Response creates response transformer
func Response(fn func(map[string]any) map[string]any) mizu.Middleware

// WithFieldMap creates field mapping transformer
func WithFieldMap(fieldMap map[string]string) mizu.Middleware

Technical Details

The transformer middleware provides a flexible architecture for modifying HTTP requests and responses:

Request Transformation

Request transformers are applied sequentially before the handler executes. Each transformer receives the *http.Request object and can modify:
  • Headers (add, set, remove)
  • URL path and query parameters
  • Request body content
The middleware supports multiple request transformers, applied in the order they are registered.

Response Transformation

Response transformation uses a custom responseRecorder that captures:
  • HTTP status code (defaults to 200 OK if not set)
  • Response headers
  • Response body bytes
The recorder intercepts all response writes, allowing transformers to modify the complete response before it’s sent to the client. Response transformers are applied sequentially and can modify:
  • Status codes (mapping or conditional changes)
  • Headers (add, set, remove)
  • Body content (transformation or replacement)

Implementation Details

  • Request transformers receive *http.Request and return an error
  • Response transformers receive (statusCode int, headers http.Header, body []byte) and return (int, http.Header, []byte, error)
  • The middleware restores the original response writer after capturing to ensure proper cleanup
  • Headers from the recorder are copied to the original writer before writing the status and body
  • Empty response bodies are handled gracefully

Best Practices

  • Use for API version compatibility
  • Keep transformations simple
  • Document transformation rules
  • Test edge cases thoroughly

Testing

The transformer middleware includes comprehensive test coverage for all transformation functions:
Test CaseDescriptionExpected Behavior
TestNewBasic middleware initializationMiddleware works with default empty options
TestAddHeaderAdding a request headerNew header is added to request and accessible in handler
TestSetHeaderSetting/overriding a request headerExisting header value is replaced with new value
TestRemoveHeaderRemoving a request headerSpecified header is deleted from request
TestRewritePathURL path rewritingRequest path is transformed from old prefix to new prefix
TestAddQueryParamAdding query parametersNew query parameter is added and encoded properly
TestTransformBodyRequest body transformationRequest body is transformed (e.g., uppercase conversion)
TestAddResponseHeaderAdding a response headerNew header is added to response
TestSetResponseHeaderSetting/overriding a response headerResponse header is set to new value, overriding handler’s value
TestRemoveResponseHeaderRemoving a response headerSpecified header is removed from response
TestTransformResponseBodyResponse body transformationResponse body content is transformed before sending
TestMapStatusCodeStatus code mappingHTTP status code is mapped from one value to another
TestReplaceBodyConditional body replacementResponse body is replaced based on status code condition
TestMultipleTransformersMultiple request and response transformersAll transformers are applied in sequence correctly