Documentation Index
Fetch the complete documentation index at: https://docs.go-mizu.dev/llms.txt
Use this file to discover all available pages before exploring further.
API Reference
This page documents all public functions, types, and options in the Contract v2 package.
Main Package
Import: github.com/go-mizu/mizu/contract/v2
Functions
Register
Registers a Go interface implementation as a Contract service.
func Register[T any](impl T, opts ...Option) *RegisteredService
| Parameter | Type | Description |
|---|
T | type parameter | The interface type that defines your API |
impl | T | Your implementation that satisfies the interface |
opts | ...Option | Optional configuration |
Returns: *RegisteredService for mounting on transports.
Example:
// todo/api.go - Your interface is defined in a package
// type API interface {
// Create(ctx context.Context, in *CreateInput) (*Todo, error)
// List(ctx context.Context) (*ListOutput, error)
// }
impl := todo.NewService()
svc := contract.Register[todo.API](impl,
contract.WithName("Todo"),
contract.WithDefaultResource("todos"),
)
Types
RegisteredService
A registered service ready to be mounted on transports.
type RegisteredService struct {
// ... internal fields
}
Methods:
| Method | Returns | Description |
|---|
Descriptor() | *ServiceDescriptor | Get service metadata |
Call(ctx, resource, method, input) | (any, error) | Invoke a method programmatically |
NewInput(resource, method) | (any, error) | Create new input instance |
ServiceDescriptor
Metadata about a registered service.
type ServiceDescriptor struct {
Name string // Service name
Description string // Optional description
Resources []*Resource // All resources
Types []*TypeInfo // All discovered types
}
Resource
A group of related methods (e.g., “todos”).
type Resource struct {
Name string // Resource name (e.g., "todos")
Methods []*Method // Methods in this resource
}
Method
Metadata for a single method.
type Method struct {
Name string // Method name (e.g., "create")
Description string // Optional description
Input *TypeInfo // Input type (nil if no input)
Output *TypeInfo // Output type (nil if no output)
HTTP *HTTPBinding // HTTP method and path
Stream StreamMode // Streaming mode if any
}
TypeInfo
Information about a type used in the API.
type TypeInfo struct {
Name string // Type name (e.g., "CreateInput")
Kind string // Type kind (struct, slice, etc.)
Schema map[string]any // JSON Schema
}
HTTPBinding
HTTP method and path for a method.
type HTTPBinding struct {
Method string // HTTP method (GET, POST, etc.)
Path string // URL path pattern
}
Options
WithName
Sets the service name:
contract.WithName("Todo")
WithDescription
Sets the service description:
contract.WithDescription("Todo management API")
WithDefaultResource
Groups all methods under a resource name:
contract.WithDefaultResource("todos")
WithResource
Groups specific methods under a resource:
contract.WithResource("users", "CreateUser", "GetUser", "ListUsers")
WithMethodHTTP
Override HTTP binding for a method:
contract.WithMethodHTTP("Archive", "POST", "/todos/{id}/archive")
WithHTTP
Set HTTP bindings for multiple methods:
contract.WithHTTP(map[string]contract.HTTPBinding{
"Create": {Method: "POST", Path: "/v1/todos"},
"Get": {Method: "GET", Path: "/v1/todos/{id}"},
})
WithDefaults
Set global defaults:
contract.WithDefaults(contract.Defaults{
BaseURL: "https://api.example.com",
})
WithStreaming
Mark a method as streaming:
contract.WithStreaming("Chat", contract.StreamSSE)
Usage Example:
svc := contract.Register[TodoAPI](impl,
contract.WithName("Todo"),
contract.WithDescription("Manages todo items"),
contract.WithDefaultResource("todos"),
)
REST Package
Import: github.com/go-mizu/mizu/contract/v2/transport/rest
Functions
Mount
Mounts REST endpoints on a router.
func Mount(router *mizu.Router, svc *contract.RegisteredService, opts ...Option)
| Parameter | Type | Description |
|---|
router | *mizu.Router | Mizu router |
svc | *RegisteredService | Registered service |
opts | ...Option | Optional configuration |
Endpoints created based on method names:
Create -> POST /{resource}
List -> GET /{resource}
Get -> GET /{resource}/{id}
Update -> PUT /{resource}/{id}
Delete -> DELETE /{resource}/{id}
Example:
rest.Mount(app.Router, svc)
// Creates: POST /todos, GET /todos, GET /todos/{id}, PUT /todos/{id}, DELETE /todos/{id}
NewHandler
Creates an HTTP handler for the service.
func NewHandler(svc *contract.RegisteredService, opts ...Option) http.Handler
Options
// Custom invoker (for middleware)
rest.WithInvoker(invoker)
// Custom path prefix
rest.WithPrefix("/api/v1")
JSON-RPC Package
Import: github.com/go-mizu/mizu/contract/v2/transport/jsonrpc
Functions
Mount
Mounts a JSON-RPC 2.0 endpoint.
func Mount(router *mizu.Router, path string, svc *contract.RegisteredService, opts ...Option)
| Parameter | Type | Description |
|---|
router | *mizu.Router | Mizu router |
path | string | URL path for the endpoint |
svc | *RegisteredService | Registered service |
opts | ...Option | Optional configuration |
Example:
jsonrpc.Mount(app.Router, "/rpc", svc)
// Methods available as: todos.create, todos.list, todos.get, etc.
NewHandler
Creates a JSON-RPC HTTP handler.
func NewHandler(svc *contract.RegisteredService, opts ...Option) http.Handler
Options
// Custom invoker (for middleware)
jsonrpc.WithInvoker(invoker)
Types
Request
type Request struct {
JSONRPC string `json:"jsonrpc"`
ID any `json:"id,omitempty"`
Method string `json:"method"`
Params json.RawMessage `json:"params,omitempty"`
}
Response
type Response struct {
JSONRPC string `json:"jsonrpc"`
ID any `json:"id,omitempty"`
Result any `json:"result,omitempty"`
Error *Error `json:"error,omitempty"`
}
Error
type Error struct {
Code int `json:"code"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
}
MCP Package
Import: github.com/go-mizu/mizu/contract/v2/transport/mcp
Functions
Mount
Mounts MCP endpoint.
func Mount(router *mizu.Router, path string, svc *contract.RegisteredService, opts ...Option)
Example:
mcp.Mount(app.Router, "/mcp", svc)
NewHandler
Creates an MCP HTTP handler.
func NewHandler(svc *contract.RegisteredService, opts ...Option) http.Handler
Options
// Server information
mcp.WithServerInfo(mcp.ServerInfo{
Name: "my-api",
Version: "1.0.0",
})
// Instructions for AI
mcp.WithInstructions("Use these tools to manage todos.")
// Allowed CORS origins
mcp.WithAllowedOrigins("https://claude.ai")
// Custom invoker (for middleware)
mcp.WithInvoker(invoker)
Types
ServerInfo
type ServerInfo struct {
Name string `json:"name"`
Version string `json:"version"`
}
OpenAPI Package
Import: github.com/go-mizu/mizu/contract/v2/transport/openapi
Functions
Mount
Mounts OpenAPI spec endpoint.
func Mount(router *mizu.Router, path string, svc *contract.RegisteredService)
Example:
openapi.Mount(app.Router, "/openapi.json", svc)
Generate
Generates OpenAPI document from service.
func Generate(svc *contract.RegisteredService) *Document
Error Types
Error
Contract error with code and message.
type Error struct {
Code ErrorCode `json:"code"`
Message string `json:"message"`
Details map[string]any `json:"details,omitempty"`
}
Methods:
| Method | Returns | Description |
|---|
Error() | string | Error message (implements error) |
HTTPStatus() | int | HTTP status code |
JSONRPCCode() | int | JSON-RPC error code |
Unwrap() | error | Wrapped cause |
WithDetail(key, value) | *Error | Add detail |
WithDetails(map) | *Error | Add multiple details |
WithCause(err) | *Error | Wrap underlying error |
Error Constructors
Convenience functions for common errors:
contract.ErrNotFound(message string) *Error // 404
contract.ErrInvalidArgument(message string) *Error // 400
contract.ErrPermissionDenied(message string) *Error // 403
contract.ErrUnauthenticated(message string) *Error // 401
contract.ErrInternal(message string) *Error // 500
contract.ErrAlreadyExists(message string) *Error // 409
contract.ErrResourceExhausted(message string) *Error // 429
contract.ErrUnimplemented(message string) *Error // 501
contract.ErrUnavailable(message string) *Error // 503
General constructors:
contract.NewError(code ErrorCode, message string) *Error
contract.Errorf(code ErrorCode, format string, args ...any) *Error
ErrorCode
All available error codes:
type ErrorCode string
const (
ErrCodeOK ErrorCode = "OK"
ErrCodeCanceled ErrorCode = "CANCELED"
ErrCodeUnknown ErrorCode = "UNKNOWN"
ErrCodeInvalidArgument ErrorCode = "INVALID_ARGUMENT"
ErrCodeDeadlineExceeded ErrorCode = "DEADLINE_EXCEEDED"
ErrCodeNotFound ErrorCode = "NOT_FOUND"
ErrCodeAlreadyExists ErrorCode = "ALREADY_EXISTS"
ErrCodePermissionDenied ErrorCode = "PERMISSION_DENIED"
ErrCodeResourceExhausted ErrorCode = "RESOURCE_EXHAUSTED"
ErrCodeFailedPrecondition ErrorCode = "FAILED_PRECONDITION"
ErrCodeAborted ErrorCode = "ABORTED"
ErrCodeOutOfRange ErrorCode = "OUT_OF_RANGE"
ErrCodeUnimplemented ErrorCode = "UNIMPLEMENTED"
ErrCodeInternal ErrorCode = "INTERNAL"
ErrCodeUnavailable ErrorCode = "UNAVAILABLE"
ErrCodeDataLoss ErrorCode = "DATA_LOSS"
ErrCodeUnauthenticated ErrorCode = "UNAUTHENTICATED"
)
Helper Functions
// Convert error to Contract error
contract.AsError(err error) *Error
// Convert HTTP status to error code
contract.HTTPStatusToErrorCode(status int) ErrorCode
Method Signatures
Contract recognizes these method patterns:
func (s *Service) Create(ctx context.Context, in *CreateInput) (*Todo, error)
Pattern 2: Output Only
func (s *Service) List(ctx context.Context) (*ListOutput, error)
func (s *Service) Delete(ctx context.Context, in *DeleteInput) error
Pattern 4: Neither
func (s *Service) Health(ctx context.Context) error
Rules:
- First parameter must be
context.Context
- Input (if any) must be a pointer to a struct
- Last return value must be
error
- Output (if any) must be a pointer to a struct
Complete Example
This example shows a complete application using the recommended package-based organization:
// todo/types.go
package todo
type Todo struct {
ID string `json:"id"`
Title string `json:"title"`
}
type CreateInput struct {
Title string `json:"title"`
}
type GetInput struct {
ID string `json:"id" path:"id"`
}
type DeleteInput struct {
ID string `json:"id" path:"id"`
}
type ListOutput struct {
Items []*Todo `json:"items"`
}
// todo/api.go
package todo
import "context"
// API defines the contract for todo operations
type API interface {
Create(ctx context.Context, in *CreateInput) (*Todo, error)
List(ctx context.Context) (*ListOutput, error)
Get(ctx context.Context, in *GetInput) (*Todo, error)
Delete(ctx context.Context, in *DeleteInput) error
}
// todo/service.go
package todo
import (
"context"
contract "github.com/go-mizu/mizu/contract/v2"
)
// Service implements todo.API
type Service struct{}
// Compile-time check
var _ API = (*Service)(nil)
func NewService() *Service {
return &Service{}
}
func (s *Service) Create(ctx context.Context, in *CreateInput) (*Todo, error) {
if in.Title == "" {
return nil, contract.ErrInvalidArgument("title is required")
}
return &Todo{ID: "1", Title: in.Title}, nil
}
func (s *Service) List(ctx context.Context) (*ListOutput, error) {
return &ListOutput{Items: []*Todo{}}, nil
}
func (s *Service) Get(ctx context.Context, in *GetInput) (*Todo, error) {
return &Todo{ID: in.ID, Title: "Sample"}, nil
}
func (s *Service) Delete(ctx context.Context, in *DeleteInput) error {
return nil
}
// main.go
package main
import (
"github.com/go-mizu/mizu"
contract "github.com/go-mizu/mizu/contract/v2"
"github.com/go-mizu/mizu/contract/v2/transport/rest"
"github.com/go-mizu/mizu/contract/v2/transport/jsonrpc"
"github.com/go-mizu/mizu/contract/v2/transport/mcp"
"github.com/go-mizu/mizu/contract/v2/transport/openapi"
"yourapp/todo"
)
func main() {
impl := todo.NewService()
// Register
svc := contract.Register[todo.API](impl,
contract.WithName("Todo"),
contract.WithDefaultResource("todos"),
)
// Create app
app := mizu.New()
// Mount transports
rest.Mount(app.Router, svc)
jsonrpc.Mount(app.Router, "/rpc", svc)
mcp.Mount(app.Router, "/mcp", svc)
openapi.Mount(app.Router, "/openapi.json", svc)
app.Listen(":8080")
}
See Also