encode

package
v0.0.0-...-3b7a441 Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package encode provides HL7 v2.x message encoding functionality.

The encode package converts structured hl7.Message objects back to their wire format representation. It supports configurable line endings, optional MLLP (Minimal Lower Layer Protocol) framing, and streaming to io.Writer.

Basic Usage

Encode a message to bytes:

enc := encode.New()
data, err := enc.Encode(msg)
if err != nil {
    log.Fatal("encode error:", err)
}
// data contains the HL7 message as bytes

Encode directly to a writer (e.g., network connection):

ctx := context.Background()
err := enc.EncodeToWriter(ctx, conn, msg)
if err != nil {
    log.Fatal("encode error:", err)
}

Encoder Options

The encoder supports functional options for configuration:

// Use CRLF line endings (for Windows compatibility)
enc := encode.New(encode.WithLineEnding("\r\n"))

// Enable MLLP framing for TCP transmission
enc := encode.New(encode.WithMLLP(true))

// Include trailing delimiters
enc := encode.New(encode.WithTrailingDelimiters(true))

// Combine multiple options
enc := encode.New(
    encode.WithMLLP(true),
    encode.WithLineEnding("\r"),
)

Line Endings

HL7 v2.x specifies carriage return (CR, 0x0D) as the segment terminator. Some systems require different line endings:

// Standard HL7 (default)
enc := encode.New(encode.WithLineEnding("\r"))

// Windows-style CRLF
enc := encode.New(encode.WithLineEnding("\r\n"))

// Unix-style LF
enc := encode.New(encode.WithLineEnding("\n"))

MLLP Framing

MLLP (Minimal Lower Layer Protocol) is the standard transport protocol for HL7 over TCP/IP. When enabled, messages are wrapped with:

  • Start block: 0x0B (vertical tab)
  • End block: 0x1C 0x0D (file separator + carriage return)

Example with MLLP framing:

enc := encode.New(encode.WithMLLP(true))
data, _ := enc.Encode(msg)
// data starts with 0x0B, ends with 0x1C 0x0D

MLLP frame structure:

<VT>MSH|^~\&|...<CR>PID|...<CR>...<FS><CR>
^                                     ^  ^
|                                     |  |
Start Block (0x0B)          End Block-+  +- CR (0x0D)
                               (0x1C)

Streaming Encoding

For large messages or network transmission, use EncodeToWriter for efficient streaming with context cancellation support:

ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

err := enc.EncodeToWriter(ctx, conn, msg)
if err != nil {
    if errors.Is(err, context.DeadlineExceeded) {
        log.Println("encode timeout")
    } else {
        log.Println("encode error:", err)
    }
}

Error Handling

Encoding errors are returned as *Error with detailed information:

data, err := enc.Encode(msg)
if err != nil {
    var encErr *encode.Error
    if errors.As(err, &encErr) {
        fmt.Printf("Encode failed: %s\n", encErr.Message)
        if encErr.Segment != "" {
            fmt.Printf("  at segment: %s\n", encErr.Segment)
        }
        if encErr.Cause != nil {
            fmt.Printf("  cause: %v\n", encErr.Cause)
        }
    }
}

Example: Complete Encoding Workflow

// Create encoder with MLLP for network transmission
enc := encode.New(
    encode.WithMLLP(true),
    encode.WithLineEnding("\r"),
)

// Parse incoming message, modify it, and send response
parser := parse.New()
msg, err := parser.Parse(incomingData)
if err != nil {
    return err
}

// Modify message
msg.Set("MSH.5", "RECEIVING_APP")
msg.Set("MSH.6", "RECEIVING_FACILITY")

// Encode and send
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()

if err := enc.EncodeToWriter(ctx, conn, msg); err != nil {
    return fmt.Errorf("failed to send message: %w", err)
}

MLLP Constants

The package exports MLLP framing constants for use in custom implementations:

encode.MLLPStartBlock      // 0x0B - vertical tab
encode.MLLPEndBlock        // 0x1C - file separator
encode.MLLPCarriageReturn  // 0x0D - carriage return

Package encode provides HL7 v2.x message encoding functionality. It converts HL7 message structures back to the wire format with configurable options for line endings, MLLP framing, and delimiters.

Index

Constants

View Source
const (
	// MLLPStartBlock is the vertical tab character that starts an MLLP frame.
	MLLPStartBlock = 0x0B
	// MLLPEndBlock is the file separator character that ends an MLLP frame.
	MLLPEndBlock = 0x1C
	// MLLPCarriageReturn is the carriage return after the end block.
	MLLPCarriageReturn = 0x0D
)

MLLP (Minimal Lower Layer Protocol) framing bytes.

View Source
const (
	// DefaultLineEnding is the standard HL7 segment terminator (carriage return).
	DefaultLineEnding = "\r"
)

Default encoder settings.

Variables

This section is empty.

Functions

This section is empty.

Types

type Encoder

type Encoder interface {
	// Encode converts an HL7 message to bytes.
	// Returns the encoded message with appropriate line endings and optional MLLP framing.
	Encode(msg hl7.Message) ([]byte, error)

	// EncodeToWriter writes an encoded HL7 message to the provided writer.
	// The context can be used for cancellation during long-running writes.
	EncodeToWriter(ctx context.Context, w io.Writer, msg hl7.Message) error
}

Encoder encodes HL7 messages to their wire format representation.

func New

func New(opts ...EncoderOption) Encoder

New creates a new Encoder with the given options. If no options are provided, default settings are used:

  • Line ending: "\r" (carriage return)
  • MLLP framing: disabled
  • Trailing delimiters: excluded

type EncoderOption

type EncoderOption func(*encoderConfig)

EncoderOption is a functional option for configuring an encoder.

func WithLineEnding

func WithLineEnding(ending string) EncoderOption

WithLineEnding sets the segment terminator string. The default is "\r" (carriage return) per HL7 specification. Some systems may require "\r\n" (CRLF) for compatibility.

func WithMLLP

func WithMLLP(enable bool) EncoderOption

WithMLLP enables or disables MLLP (Minimal Lower Layer Protocol) framing. When enabled, messages are wrapped with:

  • Start block: 0x0B (vertical tab)
  • End block: 0x1C 0x0D (file separator + carriage return)

MLLP is commonly used for TCP/IP transmission of HL7 messages.

func WithTrailingDelimiters

func WithTrailingDelimiters(include bool) EncoderOption

WithTrailingDelimiters controls whether trailing empty delimiters are included. When false (default), trailing empty fields, components, and subcomponents are omitted from the encoded output. When true, delimiters are preserved even for empty trailing elements.

type Error

type Error struct {
	// Message describes what went wrong.
	Message string
	// Segment is the segment name where the error occurred (if applicable).
	Segment string
	// Position is the segment index where the error occurred (if applicable).
	Position int
	// Cause is the underlying error that caused this encode error.
	Cause error
}

Error represents an error that occurred during message encoding.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying cause of the encode error.

type Writer

type Writer interface {
	// Write encodes and writes an HL7 message to the underlying writer.
	// The message is encoded according to the configured options.
	Write(msg hl7.Message) error

	// Flush flushes any buffered data to the underlying writer.
	Flush() error

	// Close flushes any remaining data and releases resources.
	// After Close is called, the Writer should not be used.
	Close() error
}

Writer provides a streaming interface for writing HL7 messages. It buffers writes for efficiency and supports configurable encoding options.

func NewWriter

func NewWriter(w io.Writer, opts ...EncoderOption) Writer

NewWriter creates a new Writer that writes encoded HL7 messages to w. The Writer uses buffered I/O for efficiency. Options control encoding behavior such as line endings and MLLP framing.

Jump to

Keyboard shortcuts

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