wire

package module
v3.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: MIT Imports: 3 Imported by: 4 modules, 6 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

wire

CI CodeQL Coverage Mutation Documentation Go Reference Release Go License

wire provides explicit, auditable JSON, XML, SOAP, YAML, TOML, MessagePack, CBOR, and BSON interoperability boundaries with bounded read and write APIs.

Status

The latest published stable release is v3.1.0, using github.com/faustbrian/go-wire/v3 for the v3 MessagePack admission and projection contract. Version 2 remains available for consumers not migrating, but does not include those narrowed controls. See the versioned threat model before adoption.

This source tree prepares the v3.2.0 minor release, adding optional jsonwire decode budgets, exact numbers for untyped targets and target-free validation, and xmlwire single-byte output charsets and Nillable. Its dated changelog and module version identify a release candidate, not completed publication. Adopt v3.2.0 only after its immutable release tag is published; the installation command below intentionally selects the already-published v3.1.0 release.

Requirements

  • Go 1.27.0 or later

Installation

go get github.com/faustbrian/go-wire/v3@v3.1.0

Import format packages explicitly, such as github.com/faustbrian/go-wire/v3/jsonwire or github.com/faustbrian/go-wire/v3/soap. Keep imports within the selected major.

Quickstart

var response struct {
    Status string `json:"status"`
}

err := jsonwire.DecodeReader(
    strings.NewReader(`{"status":"ok"}`),
    &response,
    jsonwire.DecodeOptions{DisallowUnknownFields: true},
)
if err != nil {
    return err
}

Each format exposes explicit options and limits. See the quickstart for XML namespace validation, SOAP envelopes, and binary-format examples.

JSON decoding rejects invalid UTF-8 by default. For third-party payloads that cannot meet RFC 8259, DecodeOptions.ReplaceInvalidUTF8 reproduces encoding/json's U+FFFD replacement in decoded strings, while raw-message and json.Unmarshaler targets still receive the original bytes, and MaxNestedLevels bounds nesting before assignment; see the cookbook.

Package Guarantees

  • bounded decode and encode paths for every supported format
  • explicit format packages instead of a lossy universal codec
  • deterministic output where the format and selected mode permit it
  • stable error classification and strict defaults
  • documented charset, depth, collection, extension, and data-shape limits
  • no HTTP policy, WSDL, schema engine, persistence, or application mapping

The format matrix is authoritative for supported and intentionally unsupported behavior. Observable choices at specification and codec seams are recorded in the specification decision register.

Documentation

Start with the documentation index, quickstart, adoption guide, and API reference. Review dependencies, evidence, and hardening before processing hostile input. Normative source pins and the conformance update process live in specification/README.md.

AI tools can use llms.txt and llms-full.txt. Support guidance is in SUPPORT.md, and release history is maintained in CHANGELOG.md.

For ecosystem-wide selection and ownership guidance, see the versioned Golib ecosystem index and its Integration and data movement family.

Development

Start with go test ./... for ordinary source work, then use make check for bounded local verification. See contributor guidance for focused format fuzzing and selected compatibility, race, integration and release checks. Mutation is optional local or scheduled assurance, not a PR prerequisite; make check-full retains explicit full assurance.

Contributing

Read CONTRIBUTING.md and follow the code of conduct. Format-specific behavior and interoperability tradeoffs must be documented explicitly.

Security

Report vulnerabilities privately according to SECURITY.md. Review docs/security.md before decoding untrusted payloads.

License

wire is available under the MIT License. Attribution and third-party policy are recorded in NOTICE and THIRD_PARTY_NOTICES.md.

Documentation navigation

Complete documentation map · Current source package map

Use the versioned ecosystem entry for package selection. The frozen compatibility cohort is separate from current package releases and unpublished source changes. Adopting them does not silently update that cohort.

Documentation

Overview

Package wire provides shared format and error primitives for structured wire-format packages.

Format-specific behavior lives in the jsonwire, xmlwire, soap, yamlwire, tomlwire, msgpackwire, cborwire, and bsonwire packages. Detection is deliberately limited to opt-in JSON/XML inspection because callers at interoperability boundaries usually know which wire format a peer promises to send.

Start with an explicit format package; DetectFormat is only a leading-byte hint. Functions own no transport, context, handles or workers. Keep borrowed inputs stable; codecs may mutate decode targets before returning an error. Finite input and output quotas are not universal heap, callback-work or deadline guarantees. Default Error text is categorical; causes and structured diagnostics are sensitive.

Example
package main

import (
	"fmt"
	"log"
	"strings"

	"github.com/faustbrian/go-wire/v3/jsonwire"
)

func main() {
	var response struct {
		Status string `json:"status"`
	}
	err := jsonwire.DecodeReader(
		strings.NewReader(`{"status":"ok"}`),
		&response,
		jsonwire.DecodeOptions{DisallowUnknownFields: true},
	)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(response.Status)
}
Output:
ok
Example (BsonRoundTrip)
package main

import (
	"bytes"
	"fmt"
	"log"

	"github.com/faustbrian/go-wire/v3/bsonwire"
)

func main() {
	value := bsonwire.D{{Key: "status", Value: "ok"}}
	var output bytes.Buffer
	if err := bsonwire.EncodeWriter(&output, value, bsonwire.EncodeOptions{}); err != nil {
		log.Fatal(err)
	}
	var decoded bsonwire.M
	if err := bsonwire.Decode(output.Bytes(), &decoded, bsonwire.DecodeOptions{}); err != nil {
		log.Fatal(err)
	}
	fmt.Println(decoded["status"])
}
Output:
ok
Example (CborRoundTrip)
package main

import (
	"bytes"
	"fmt"
	"log"

	"github.com/faustbrian/go-wire/v3/cborwire"
)

func main() {
	value := struct {
		Status string `cbor:"status"`
	}{Status: "ok"}
	var output bytes.Buffer
	if err := cborwire.EncodeWriter(&output, value, cborwire.EncodeOptions{}); err != nil {
		log.Fatal(err)
	}
	var decoded struct {
		Status string `cbor:"status"`
	}
	if err := cborwire.Decode(output.Bytes(), &decoded, cborwire.DecodeOptions{}); err != nil {
		log.Fatal(err)
	}
	fmt.Println(decoded.Status)
}
Output:
ok
Example (JsonWriter)
package main

import (
	"bytes"
	"fmt"
	"log"

	"github.com/faustbrian/go-wire/v3/jsonwire"
)

func main() {
	var output bytes.Buffer
	err := jsonwire.EncodeWriter(&output, map[string]int{"z": 2, "a": 1}, jsonwire.EncodeOptions{})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(output.String())
}
Output:
{"a":1,"z":2}
Example (MessagePackRoundTrip)
package main

import (
	"bytes"
	"fmt"
	"log"

	"github.com/faustbrian/go-wire/v3/msgpackwire"
)

func main() {
	value := struct {
		Status string `msgpack:"status"`
	}{Status: "ok"}
	var output bytes.Buffer
	if err := msgpackwire.EncodeWriter(&output, value, msgpackwire.EncodeOptions{}); err != nil {
		log.Fatal(err)
	}
	var decoded struct {
		Status string `msgpack:"status"`
	}
	if err := msgpackwire.Decode(output.Bytes(), &decoded, msgpackwire.DecodeOptions{}); err != nil {
		log.Fatal(err)
	}
	fmt.Println(decoded.Status)
}
Output:
ok
Example (SoapFault)
package main

import (
	"errors"
	"fmt"
	"log"

	"github.com/faustbrian/go-wire/v3"
	"github.com/faustbrian/go-wire/v3/soap"
)

func main() {
	payload, err := soap.MarshalFault(soap.Fault{
		Version: soap.Version11,
		Code:    "soap:Server",
		Reason:  "Carrier unavailable",
	})
	if err != nil {
		log.Fatal(err)
	}
	_, err = soap.Parse(payload, soap.ParseOptions{})
	if errors.Is(err, wire.ErrSOAPFault) {
		fmt.Println("fault")
	}
}
Output:
fault
Example (SoapWriter)
package main

import (
	"bytes"
	"encoding/xml"
	"fmt"
	"log"

	"github.com/faustbrian/go-wire/v3/soap"
)

func main() {
	var output bytes.Buffer
	request := struct {
		XMLName xml.Name `xml:"Ping"`
	}{}
	if err := soap.EncodeWriter(&output, soap.Version11, nil, request, soap.EncodeOptions{}); err != nil {
		log.Fatal(err)
	}
	fmt.Println(output.String())
}
Output:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><Ping></Ping></soap:Body></soap:Envelope>
Example (TomlRoundTrip)
package main

import (
	"bytes"
	"fmt"
	"log"

	"github.com/faustbrian/go-wire/v3/tomlwire"
)

func main() {
	value := struct {
		Status string `toml:"status"`
	}{Status: "ok"}
	var output bytes.Buffer
	if err := tomlwire.EncodeWriter(&output, value, tomlwire.EncodeOptions{}); err != nil {
		log.Fatal(err)
	}
	var decoded struct {
		Status string `toml:"status"`
	}
	if err := tomlwire.Decode(output.Bytes(), &decoded, tomlwire.DecodeOptions{}); err != nil {
		log.Fatal(err)
	}
	fmt.Println(decoded.Status)
}
Output:
ok
Example (Xml)
package main

import (
	"encoding/xml"
	"fmt"
	"log"

	"github.com/faustbrian/go-wire/v3/xmlwire"
)

func main() {
	var shipment struct {
		XMLName xml.Name `xml:"urn:vendor Shipment"`
		ID      int      `xml:"urn:vendor ID"`
	}
	payload := []byte(`<v:Shipment xmlns:v="urn:vendor"><v:ID>42</v:ID></v:Shipment>`)
	err := xmlwire.Decode(payload, &shipment, xmlwire.DecodeOptions{
		ExpectedRoot: xml.Name{Space: "urn:vendor", Local: "Shipment"},
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(shipment.ID)
}
Output:
42
Example (XmlWriter)
package main

import (
	"bytes"
	"encoding/xml"
	"fmt"
	"log"

	"github.com/faustbrian/go-wire/v3/xmlwire"
)

func main() {
	var output bytes.Buffer
	value := struct {
		XMLName xml.Name `xml:"Status"`
		Value   string   `xml:",chardata"`
	}{Value: "ok"}
	if err := xmlwire.EncodeWriter(&output, value, xmlwire.EncodeOptions{}); err != nil {
		log.Fatal(err)
	}
	fmt.Println(output.String())
}
Output:
<Status>ok</Status>
Example (YamlRoundTrip)
package main

import (
	"bytes"
	"fmt"
	"log"

	"github.com/faustbrian/go-wire/v3/yamlwire"
)

func main() {
	value := struct {
		Status string `yaml:"status"`
	}{Status: "ok"}
	var output bytes.Buffer
	if err := yamlwire.EncodeWriter(&output, value, yamlwire.EncodeOptions{}); err != nil {
		log.Fatal(err)
	}
	var decoded struct {
		Status string `yaml:"status"`
	}
	if err := yamlwire.Decode(output.Bytes(), &decoded, yamlwire.DecodeOptions{}); err != nil {
		log.Fatal(err)
	}
	fmt.Println(decoded.Status)
}
Output:
ok

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrParse is the errors.Is category for malformed input or read failures.
	ErrParse = errors.New("parse failure")
	// ErrValidation is the errors.Is category for invalid options, assignments or values.
	ErrValidation = errors.New("validation failure")
	// ErrUnsupportedFormat is the errors.Is category for unsupported formats or features.
	ErrUnsupportedFormat = errors.New("unsupported format")
	// ErrEnvelope is the errors.Is category for invalid SOAP structure.
	ErrEnvelope = errors.New("envelope failure")
	// ErrSOAPFault is the errors.Is category for a valid SOAP fault response.
	ErrSOAPFault = errors.New("SOAP fault")
	// ErrWrite is the errors.Is category for destination write failures.
	ErrWrite = errors.New("write failure")
	// ErrSizeLimit is the errors.Is category for byte or structural budget refusal.
	ErrSizeLimit = errors.New("size limit exceeded")
	// ErrTarget is the errors.Is category for invalid decode targets.
	ErrTarget = errors.New("invalid target")
	// ErrEncode is the errors.Is category for codec serialization failure.
	ErrEncode = errors.New("encode failure")
)

Functions

This section is empty.

Types

type Error

type Error struct {
	// Kind selects the stable public category used by Error and Is.
	Kind ErrorKind
	// Format identifies the codec; it is inspectable metadata, not rendered by Error.
	Format Format
	// Op contains diagnostic operation text; caller-supplied values are not sanitized.
	Op string
	// Err retains the original cause for Unwrap/Is/As and can contain sensitive input.
	Err error
}

Error describes a wire-format failure using stable categories. Causes and structured fields remain inspectable, not sanitized; redact before disclosure. Error/Is/Unwrap require a non-nil receiver. There is no automatic cause copy.

func (*Error) Error

func (e *Error) Error() string

Error returns a stable classification without rendering diagnostic fields or the underlying cause, which may contain untrusted wire data.

func (*Error) Is

func (e *Error) Is(target error) bool

Is reports whether target is the sentinel associated with the error kind or matches the underlying cause.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying format-specific failure, if any.

type ErrorKind

type ErrorKind string

ErrorKind classifies a failure independently of its underlying cause.

const (
	// ErrorKindParse classifies malformed input and reader failures.
	ErrorKindParse ErrorKind = "parse"
	// ErrorKindValidation classifies option, value and semantic validation failures.
	ErrorKindValidation ErrorKind = "validation"
	// ErrorKindUnsupported classifies unsupported formats or codec features.
	ErrorKindUnsupported ErrorKind = "unsupported"
	// ErrorKindEnvelope classifies invalid SOAP envelope/body/fault structure.
	ErrorKindEnvelope ErrorKind = "envelope"
	// ErrorKindFault classifies a valid SOAP fault response.
	ErrorKindFault ErrorKind = "fault"
	// ErrorKindWrite classifies a destination failure after successful serialization.
	ErrorKindWrite ErrorKind = "write"
	// ErrorKindSizeLimit classifies a configured byte or structural budget refusal.
	ErrorKindSizeLimit ErrorKind = "size-limit"
	// ErrorKindTarget classifies nil, typed-nil or non-pointer decode targets.
	ErrorKindTarget ErrorKind = "target"
	// ErrorKindEncode classifies codec serialization failures where the format uses this
	// category.
	ErrorKindEncode ErrorKind = "encode"
)

type Format

type Format string

Format identifies a supported structured wire format.

const (
	// FormatJSON identifies JSON text, including scalar values when explicitly decoded.
	FormatJSON Format = "json"
	// FormatXML identifies XML documents, not a schema or canonicalization profile.
	FormatXML Format = "xml"
	// FormatSOAP identifies SOAP envelopes; detection deliberately reports them as XML.
	FormatSOAP Format = "soap"
	// FormatYAML identifies YAML streams, not a JSON-compatible value model.
	FormatYAML Format = "yaml"
	// FormatTOML identifies TOML documents.
	FormatTOML Format = "toml"
	// FormatMessagePack names the MessagePack binary format.
	FormatMessagePack Format = "msgpack"
	// FormatCBOR identifies CBOR items; select their deterministic profile explicitly.
	FormatCBOR Format = "cbor"
	// FormatBSON identifies complete BSON documents, not arbitrary binary values.
	FormatBSON Format = "bson"
)

func DetectFormat

func DetectFormat(payload []byte) (Format, error)

DetectFormat distinguishes JSON from XML using the first significant byte. SOAP is returned as XML because reliably identifying a SOAP envelope requires parsing its namespace; use the soap package when SOAP is expected. This is not syntax validation: only {/[ and < are hints, so valid JSON scalars are unsupported. It trims whitespace and one UTF-8 BOM without mutating input; unsupported/empty payloads match ErrUnsupportedFormat. There is no byte quota.

Example
package main

import (
	"fmt"
	"log"

	"github.com/faustbrian/go-wire/v3"
)

func main() {
	format, err := wire.DetectFormat([]byte(`{"status":"ok"}`))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(format)
}
Output:
json

Directories

Path Synopsis
Package bsonwire provides bounded BSON document decoding and encoding.
Package bsonwire provides bounded BSON document decoding and encoding.
Package cborwire provides bounded CBOR decoding and deterministic encoding.
Package cborwire provides bounded CBOR decoding and deterministic encoding.
cmd
semvercheck command
Command semvercheck validates release-tag syntax or prints the next stable patch/minor/major tag using internal/semver.
Command semvercheck validates release-tag syntax or prints the next stable patch/minor/major tag using internal/semver.
internal
outputlimit
Package outputlimit supplies New for private retained-output quotas, not codec allocation or atomic publication.
Package outputlimit supplies New for private retained-output quotas, not codec allocation or atomic publication.
semver
Package semver supplies release-script tag syntax and stable bump helpers.
Package semver supplies release-script tag syntax and stable bump helpers.
valuecheck
Package valuecheck uses Validate for active-path cycle/depth admission before encoding.
Package valuecheck uses Validate for active-path cycle/depth admission before encoding.
Package jsonwire provides bounded, strict JSON helpers for interoperability boundaries where encoding/json's low-level defaults need explicit policy.
Package jsonwire provides bounded, strict JSON helpers for interoperability boundaries where encoding/json's low-level defaults need explicit policy.
Package msgpackwire provides bounded MessagePack decoding and deterministic encoding.
Package msgpackwire provides bounded MessagePack decoding and deterministic encoding.
Package soap provides transport-neutral SOAP 1.1 and SOAP 1.2 envelope, body, and fault primitives while preserving access to the original XML.
Package soap provides transport-neutral SOAP 1.1 and SOAP 1.2 envelope, body, and fault primitives while preserving access to the original XML.
Package tomlwire provides bounded, strict TOML document decoding and deterministic encoding.
Package tomlwire provides bounded, strict TOML document decoding and deterministic encoding.
Package xmlwire provides bounded XML encoding and decoding with explicit namespace, root-element, strictness, and character-set policy.
Package xmlwire provides bounded XML encoding and decoding with explicit namespace, root-element, strictness, and character-set policy.
Package yamlwire provides bounded, explicit YAML 1.2 decoding and deterministic encoding.
Package yamlwire provides bounded, explicit YAML 1.2 decoding and deterministic encoding.

Jump to

Keyboard shortcuts

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