json

package
v1.21.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 24, 2026 License: MIT Imports: 3 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Middleware

func Middleware() func(ctx *velaros.Context)

Middleware provides JSON message format support for Velaros WebSocket connections. It handles parsing incoming JSON messages and serializing outgoing messages according to the Velaros JSON message envelope format.

Message Format

Incoming messages should be JSON objects with the following structure:

{
  "id": "optional-message-id",      // For request/reply correlation
  "path": "/route/path",            // Required: determines which handler to execute
  "data": { /* your data here */ }  // Optional: message payload
}

Outgoing messages are automatically wrapped in an envelope:

{
  "id": "message-id",               // Present if replying or making a request
  "data": { /* your response */ }   // Your response data
}

Special Response Types

The middleware provides special handling for certain response types:

  • Error (string) -> {"error": "message"}
  • FieldError/[]FieldError -> {"error": "Validation error", "fields": [...]}
  • string -> {"message": "your string"}
  • Other types -> {"data": yourData}

Usage

router := velaros.NewRouter()
router.Use(json.Middleware())

router.Bind("/users/:id", func(ctx *velaros.Context) {
    var req GetUserRequest
    ctx.ReceiveInto(&req)  // Automatically uses JSON unmarshaling
    ctx.Send(user)       // Automatically serialized to JSON
})

The middleware also validates the Sec-WebSocket-Protocol header, expecting "velaros-json" if present.

Types

type Error

type Error string

Error represents a JSON wrapped error. If you want to return a JSON wrapped error, you can use this type. The JSON response will be {"error": "your error message"}.

type FieldError

type FieldError struct {
	Field string
	Error string
}

A FieldError can be used as a response body to indicate that a message body failed validation. The response will be a JSON object with the field name as the key and the error message as the value. A slice of FieldErrors can also be used to return multiple validation errors. The response will be a JSON object like { "error": "Validation error", "fields": [ { "field1": "error message" }, { "field2": "error message" } ] }.

type M

type M map[string]any

M is shorthand for a map[string]any. It is provided as a convenience for defining JSON objects in a more concise manner.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL