Skip to content
Proto Packages & Runtime

Proto Packages & Runtime

Sphere extends Protobuf with specialized packages and provides a runtime layer that makes building HTTP APIs clean and efficient.

Proto Packages Overview

Sphere includes focused Protobuf packages that keep HTTP binding, errors, and custom options declarative. These annotations power Sphere’s generators and help maintain consistent, type-safe APIs.

sphere/binding

Purpose:

  • Declare where each field binds from (URI, query, body, header, form)
  • Set message/oneof defaults and auto-tags for generated structs
  • Work seamlessly with Sphere’s request binding helpers

Use when:

  • You want explicit, generator-driven request parsing rules
  • You prefer consistent struct tags without hand editing

Example:

message GetUserRequest {
  int64 user_id = 1 [(sphere.binding.location) = BINDING_LOCATION_URI];
  repeated string fields = 2 [(sphere.binding.location) = BINDING_LOCATION_QUERY];
  string auth_token = 3 [(sphere.binding.location) = BINDING_LOCATION_HEADER];
}

See API Definitions Guide for detailed examples.

sphere/errors

Purpose:

  • Define typed error enums with HTTP status, reason, and message
  • Generate helpers to wrap causes and produce uniform JSON errors
  • Map error codes to HTTP status codes automatically

Use when:

  • You need consistent error shapes across services and clients
  • You want programmatic access to status/code/reason/message

Example:

enum UserError {
  option (sphere.errors.default_status) = 500;
  
  USER_ERROR_NOT_FOUND = 1001 [(sphere.errors.options) = {
    status: 404
    reason: "USER_NOT_FOUND"
    message: "User not found"
  }];
}

See Error Handling Guide for implementation details.

sphere/options

Purpose:

  • Attach simple key/value metadata to RPC methods
  • Let generators consume options for advanced routing or transports

Use when:

  • You build adapters beyond HTTP
  • You need custom routing hints or generator options

Runtime Layer

Sphere’s HTTP runtime is split in two:

  • httpx — router/context/handler interfaces, plus adapters for Gin, Fiber, Echo, and Hertz
  • server/httpz — JSON envelopes, WithJson, and AbortWithJsonError on top of httpx

Official templates still use Gin as the default engine, but generated code talks to httpx, not *gin.Context.

Core Components

Response Wrappers:

  • httpz.WithJson[T]: wraps a handler returning (T, error) and serializes success to DataResponse[T]
  • httpz.AbortWithJsonError: normalizes errors to ErrorResponse with HTTP status, application code, and a user-facing message

Request Binding:

  • httpx.Context methods: BindJSON, BindQuery, BindURI, BindHeader, BindForm
  • Struct tags come from sphere/binding via protoc-gen-sphere-binding

Server Features:

  • Docs Server: auxiliary HTTP server for Swagger UI
  • File / proxy helpers: server/service/file, server/service/reverseproxy
  • Middleware: auth, CORS, online tracking, rate limiting, selector

Typical Request Flow

  1. Protobuf + protoc-gen-sphere generate handler plumbing
  2. Request arrives at an httpx adapter (Gin by default)
  3. Handler binds request data to generated structs (using sphere/binding tags)
  4. Service method executes business logic, returns data or a typed error
  5. httpz.WithJson writes DataResponse or routes the error through AbortWithJsonError

Example Handler

// Generated by protoc-gen-sphere
func _UserService_GetUser0_HTTP_Handler(srv UserServiceHTTPServer) httpx.Handler {
    return httpz.WithJson(func(ctx httpx.Context) (*User, error) {
        var in GetUserRequest
        if err := ctx.BindHeader(&in); err != nil {
            return nil, err
        }
        if err := ctx.BindQuery(&in); err != nil {
            return nil, err
        }
        if err := ctx.BindURI(&in); err != nil {
            return nil, err
        }
        return srv.GetUser(ctx.Context(), &in)
    })
}

Extensibility

  • Custom Router Types: swap Gin for Fiber, Echo, or Hertz via httpx adapters and protoc-gen-sphere router_type / context_type flags
  • Response Envelope: override data_resp_type / error_resp_type / server_handler_func
  • Error Parser: httpz.SetDefaultErrorParser to merge validation or domain-specific errors
  • Debug leaks: httpz.SetDebugMode(true) includes err.Error() in ErrorResponse.Error; production leaves it empty

See HTTP Runtime for envelopes, debug mode, and adapter wiring.

Last updated on