hl7

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Apr 6, 2026 License: MIT Imports: 19 Imported by: 0

README

hl7 🏥

A comprehensive Go library for parsing, encoding, and manipulating HL7 v2.x healthcare messages.

English | 中文

Go Version License Test Coverage


English

Features
  • 🔍 Full HL7 v2.x Support - Parse and encode all HL7 v2.x message types (2.3, 2.4, 2.5, etc.)
  • Struct Marshaling - Map HL7 data to Go structs using intuitive hl7 tags
  • 🌊 Streaming Parser - Memory-efficient parsing with MLLP frame support
  • 🌐 MLLP Network Transport - Built-in client/server for HL7 over TCP with TLS support
  • Message Validation - Flexible validation with built-in and custom rules
  • 📝 ACK/NAK Generation - Automatic acknowledgment message creation
  • 🔄 Bidirectional Conversion - Parse HL7 to structs, marshal structs back to HL7
  • 📊 Schema-less Parsing - Access fields without predefined structs using Get() method
  • 🔧 Segment Helpers - Convenient methods for common segments (PID, MSH, PV1, OBR, OBX, NK1, DG1)
Installation
go get github.com/wsyqn6/hl7

Requires Go 1.26 or later.

Quick Start
Parsing a Message
package main

import (
    "fmt"
    "log"

    "github.com/wsyqn6/hl7"
)

func main() {
    data := []byte(`MSH|^~\&|SENDING|FACILITY|||202401151200||ADT^A01|MSG001|P|2.5
PID|1||12345^^^MRN||Smith^John^A||19800115|M`)

    msg, err := hl7.Parse(data)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Message Type: %s\n", msg.Type())
    fmt.Printf("Control ID: %s\n", msg.ControlID())

    // Access PID segment
    if pid, ok := msg.Segment("PID"); ok {
        fmt.Printf("Patient: %s %s\n", pid.Component(5, 2), pid.Component(5, 1))
        fmt.Printf("DOB: %s, Gender: %s\n", pid.Field(7), pid.Field(8))
    }
}
Struct Marshaling
type Patient struct {
    MRN       string `hl7:"PID.3.1"`
    LastName  string `hl7:"PID.5.1"`
    FirstName string `hl7:"PID.5.2"`
    DOB       string `hl7:"PID.7"`
    Gender    string `hl7:"PID.8"`
}

var patient Patient
if err := hl7.Unmarshal(data, &patient); err != nil {
    log.Fatal(err)
}

fmt.Printf("Patient: %s, %s (MRN: %s)\n", patient.LastName, patient.FirstName, patient.MRN)
Advanced Struct Mapping

Optional Fields:

type Patient struct {
    MRN       string `hl7:"PID.3.1"`
    LastName  string `hl7:"PID.5.1"`
    Phone     string `hl7:"PID.13,optional"`  // Optional - won't error if missing
}

Nested Struct with Components:

type PersonName struct {
    FamilyName  string `hl7:"1"`
    GivenName   string `hl7:"2"`
    MiddleName  string `hl7:"3"`
}

type Patient struct {
    MRN     string     `hl7:"PID.3.1"`
    Name    PersonName `hl7:"PID.5"`
}
Schema-less Parsing

Access fields without predefined structs:

// Simple field access
lastName, _ := msg.Get("PID.5.1")
firstName, _ := msg.Get("PID.5.2")

// Component access
patientID := msg.MustGet("PID.3")      // Full field
mrn := msg.MustGet("PID.3.1")          // First component

// Repeated segments
wbc := msg.MustGet("OBX[1].5")         // First OBX observation value
rbc := msg.MustGet("OBX[2].5")         // Second OBX observation value
Segment Helpers

Convenient methods for common segments:

// PID segment
pid := msg.PID()
fmt.Printf("Patient: %s, %s\n", pid.LastName(), pid.FirstName())
fmt.Printf("DOB: %s, Gender: %s\n", pid.DateOfBirth(), pid.Gender())

// MSH segment
msh := msg.MSH()
fmt.Printf("From: %s@%s\n", msh.SendingApplication(), msh.SendingFacility())

// OBX results (repeated)
for _, obx := range msg.AllOBX() {
    fmt.Printf("%s: %s %s\n", obx.ObservationIdentifierCode(), obx.ObservationValue(), obx.Units())
}
Message Type Examples

ADT (Admission/Discharge/Transfer) Message:

// ADT^A01 - Patient Admission
adtMsg := []byte(`MSH|^~\&|ADT_SYS|HOSPITAL|||^202401151200||ADT^A01|CTRL|P|2.5
PID|1||12345^^^MRN||Smith^John^A||19800115|M|||123 Main St^^Springfield^IL^62701||555-1234
PV1|1|I|ICU^Room101^BED1^^^SEC^ICU|||DR001^Dr. Smith^John^MD|||ICU|||||||||ADM`)

msg, _ := hl7.Parse(adtMsg)
pid := msg.PID()
fmt.Printf("Patient: %s %s\n", pid.FirstName(), pid.LastName())
fmt.Printf("Admission Type: %s\n", msg.PV1().AdmissionType())

ORU (Observation Result) Message:

// ORU^R01 - Laboratory Results
oruMsg := []byte(`MSH|^~\&|LAB_SYS|HOSPITAL|||^202401151200||ORU^R01|CTRL|P|2.5
PID|1||12345^^^MRN||Smith^John^A||19800115|M
OBR|1||12345|LAB001^CBC^L|||202401151000|||LAB||||||DR001
OBX|1|NM|WBC^WBC^LN||7.5|x10^3/uL^3^1^ML||4.5-11.0|N|||F
OBX|2|NM|RBC^RBC^LN||4.8|x10^6/uL^3^2^ML||4.5-5.5|N|||F
OBX|3|NM|HGB^Hemoglobin^LN||14.2|g/dL^3^3^ML||12.0-17.0|N|||F`)

msg, _ := hl7.Parse(oruMsg)
for _, obx := range msg.AllOBX() {
    fmt.Printf("%s: %s %s\n", obx.ObservationIdentifierCode(), obx.ObservationValue(), obx.Units())
}

ORM (Order) Message:

// ORM^O01 - General Order
ormMsg := []byte(`MSH|^~\&|ORD_SYS|HOSPITAL|||^202401151200||ORM^O01|CTRL|P|2.5
PID|1||12345^^^MRN||Smith^John^A||19800115|M
ORC|RE|12345|ORD001|CBC^LAB^L||1|||DR001^Dr. Smith^John^MD|||202401151200
OBR|1||12345|ORD001|CBC^LAB^L|||202401151200|||LAB||||||DR001`)

msg, _ := hl7.Parse(ormMsg)
orc := msg.ORC()
fmt.Printf("Order Control: %s\n", orc.OrderStatus())
TLS MLLP Server

Secure MLLP server with TLS:

handler := func(ctx context.Context, msg *hl7.Message) (*hl7.Message, error) {
    return hl7.Generate(msg, hl7.Accept())
}

server := hl7.NewServer(":2575", handler,
    hl7.WithTLS(nil),  // Uses cert/key files
)
if err := server.ListenAndServeTLS("cert.pem", "key.pem"); err != nil {
    log.Fatal(err)
}
Validation
validator := hl7.NewValidator(
    hl7.Required("MSH.9"),
    hl7.Required("PID.3.1"),
    hl7.OneOf("PID.8", "M", "F", "O", "U"),
    hl7.Pattern("PID.7", `^\d{8}$`),
)

if errors := validator.Validate(msg); len(errors) > 0 {
    for _, err := range errors {
        fmt.Printf("Validation error at %s: %s\n", err.Location, err.Message)
    }
}
MLLP Server
handler := func(ctx context.Context, msg *hl7.Message) (*hl7.Message, error) {
    fmt.Printf("Received: %s\n", msg.Type())
    return hl7.Generate(msg, hl7.Accept())
}

server := hl7.NewServer(":2575", handler)
if err := server.ListenAndServe(); err != nil {
    log.Fatal(err)
}
MLLP Client with Retry
client, err := hl7.Dial("localhost:2575",
    hl7.WithRetry(3, 100*time.Millisecond),  // 3 retries with 100ms initial delay
)
if err != nil {
    log.Fatal(err)
}
defer client.Close()

// SendWithRetry automatically retries on failure
ack, err := client.SendWithRetry(ctx, msg)
MLLP Client Pool
pool := hl7.NewClientPool("localhost:2575",
    hl7.WithPoolSize(10),  // Max 10 clients in pool
    hl7.WithRetry(2, 50*time.Millisecond),
)
defer pool.Close()

// Get client from pool, send, return to pool
ack, err := pool.Send(ctx, msg)
API Reference
Function Description
Parse(data []byte) Parse raw HL7 data into a Message
ParseString(s string) Parse HL7 from a string
Encode(msg *Message) Encode Message to bytes
Unmarshal(data []byte, v interface{}) Unmarshal HL7 into a struct
Marshal(v interface{}) Marshal a struct to HL7 bytes
msg.Get(location) Get field value by location (e.g., "PID.5.1")
msg.MustGet(location) Get field value, panic on error
msg.GetAllRepetitions(location) Get all repetitions of a field
msg.CountSegment(name) Count segments by name
msg.HasSegment(name) Check if segment exists
msg.ParseLocation(location) Parse location string to Location struct
msg.Iterate() Iterate over all segments
msg.Stats() Get message statistics
seg.Repetitions(fieldIdx) Get all repetitions of a field
seg.Components(fieldIdx) Get all components of a field
Generate(msg *Message, opts ...ACKOption) Generate ACK/NAK response
NewValidator(rules ...Rule) Create a message validator
NewServer(addr string, handler Handler) Create MLLP server
Dial(addr string) Create MLLP client
DialTLS(addr string, config) Create MLLP client with TLS
NewClientPool(addr) Create MLLP client pool
Segment Helpers
Helper Description
msg.PID() Get PID segment helper
msg.MSH() Get MSH segment helper
msg.PV1() Get PV1 segment helper
msg.OBR() Get OBR segment helper
msg.OBX() Get first OBX segment helper
msg.AllOBX() Get all OBX segments
msg.NK1() Get NK1 segment helper
msg.DG1() Get DG1 segment helper
License

MIT License - see LICENSE for details.


中文

功能特性
  • 🔍 完整的 HL7 v2.x 支持 - 解析和编码所有 HL7 v2.x 消息类型(2.3、2.4、2.5 等)
  • 结构体序列化 - 通过直观的 hl7 标签将 HL7 数据映射到 Go 结构体
  • 🌊 流式解析器 - 高效内存使用的流式解析,支持 MLLP 帧
  • 🌐 MLLP 网络传输 - 内置的 HL7 over TCP 客户端/服务器,支持 TLS
  • 消息验证 - 灵活的验证规则,支持内置和自定义规则
  • 📝 ACK/NAK 生成 - 自动创建确认和拒绝消息
  • 🔄 双向转换 - 解析 HL7 为结构体,将结构体编组回 HL7
  • 📊 无模式解析 - 使用 Get() 方法无需预定义结构体即可访问字段
  • 🔧 段帮助函数 - 常用段(PID、MSH、PV1、OBR、OBX、NK1、DG1)的便捷方法
安装
go get github.com/wsyqn6/hl7

需要 Go 1.26 或更高版本。

快速开始
解析消息
package main

import (
    "fmt"
    "log"

    "github.com/wsyqn6/hl7"
)

func main() {
    data := []byte(`MSH|^~\&|发送系统|医院|||202401151200||ADT^A01|MSG001|P|2.5
PID|1||12345^^^MRN||张三^李||19800115|M`)

    msg, err := hl7.Parse(data)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("消息类型: %s\n", msg.Type())
    fmt.Printf("控制ID: %s\n", msg.ControlID())

    // 访问 PID 段
    if pid, ok := msg.Segment("PID"); ok {
        fmt.Printf("患者: %s %s\n", pid.Component(5, 2), pid.Component(5, 1))
        fmt.Printf("出生日期: %s, 性别: %s\n", pid.Field(7), pid.Field(8))
    }
}
结构体序列化
type Patient struct {
    MRN       string `hl7:"PID.3.1"`
    LastName  string `hl7:"PID.5.1"`
    FirstName string `hl7:"PID.5.2"`
    DOB       string `hl7:"PID.7"`
    Gender    string `hl7:"PID.8"`
}

var patient Patient
if err := hl7.Unmarshal(data, &patient); err != nil {
    log.Fatal(err)
}

fmt.Printf("患者: %s, %s (病历号: %s)\n", patient.LastName, patient.FirstName, patient.MRN)
无模式解析

无需预定义结构体即可访问字段:

// 简单字段访问
lastName, _ := msg.Get("PID.5.1")
firstName, _ := msg.Get("PID.5.2")

// 组件访问
patientID := msg.MustGet("PID.3")     // 完整字段
mrn := msg.MustGet("PID.3.1")          // 第一组件

// 重复段
wbc := msg.MustGet("OBX[1].5")        // 第一个 OBX 观察值
rbc := msg.MustGet("OBX[2].5")        // 第二个 OBX 观察值
段帮助函数

常用段的便捷方法:

// PID 段
pid := msg.PID()
fmt.Printf("患者: %s, %s\n", pid.LastName(), pid.FirstName())
fmt.Printf("出生日期: %s, 性别: %s\n", pid.DateOfBirth(), pid.Gender())

// MSH 段
msh := msg.MSH()
fmt.Printf("来自: %s@%s\n", msh.SendingApplication(), msh.SendingFacility())

// OBX 结果(重复段)
for _, obx := range msg.AllOBX() {
    fmt.Printf("%s: %s %s\n", obx.ObservationIdentifierCode(), obx.ObservationValue(), obx.Units())
}
TLS MLLP 服务器

支持 TLS 的安全 MLLP 服务器:

handler := func(ctx context.Context, msg *hl7.Message) (*hl7.Message, error) {
    return hl7.Generate(msg, hl7.Accept())
}

server := hl7.NewServer(":2575", handler,
    hl7.WithTLS(nil),  // 使用证书/密钥文件
)
if err := server.ListenAndServeTLS("cert.pem", "key.pem"); err != nil {
    log.Fatal(err)
}
消息验证
validator := hl7.NewValidator(
    hl7.Required("MSH.9"),      // 消息类型必填
    hl7.Required("PID.3.1"),    // 患者ID必填
    hl7.OneOf("PID.8", "M", "F", "O", "U"),  // 有效的性别代码
    hl7.Pattern("PID.7", `^\d{8}$`),  // 出生日期格式 YYYYMMDD
)

if errors := validator.Validate(msg); len(errors) > 0 {
    for _, err := range errors {
        fmt.Printf("验证错误 [%s]: %s\n", err.Location, err.Message)
    }
}
MLLP 服务器
handler := func(ctx context.Context, msg *hl7.Message) (*hl7.Message, error) {
    fmt.Printf("收到消息: %s\n", msg.Type())
    return hl7.Generate(msg, hl7.Accept())
}

server := hl7.NewServer(":2575", handler)
if err := server.ListenAndServe(); err != nil {
    log.Fatal(err)
}
MLLP 客户端(重试机制)
client, err := hl7.Dial("localhost:2575",
    hl7.WithRetry(3, 100*time.Millisecond),  // 3次重试,初始延迟100ms
)
defer client.Close()

// 自动重试发送
ack, err := client.SendWithRetry(ctx, msg)
MLLP 连接池
pool := hl7.NewClientPool("localhost:2575",
    hl7.WithPoolSize(10),  // 最多10个客户端
    hl7.WithRetry(2, 50*time.Millisecond),
)
defer pool.Close()

// 从池中获取客户端发送
ack, err := pool.Send(ctx, msg)
API 参考
函数 描述
Parse(data []byte) 将原始 HL7 数据解析为 Message
ParseString(s string) 从字符串解析 HL7
Encode(msg *Message) 将 Message 编码为字节
Unmarshal(data []byte, v interface{}) 将 HL7 反序列化为结构体
Marshal(v interface{}) 将结构体编组为 HL7 字节
msg.Get(location) 按位置获取字段值(如 "PID.5.1")
msg.MustGet(location) 获取字段值,错误时 panic
msg.GetAllRepetitions(location) 获取字段的所有重复值
msg.CountSegment(name) 按名称统计段数量
msg.HasSegment(name) 检查段是否存在
msg.ParseLocation(location) 解析位置字符串为 Location 结构体
msg.Iterate() 遍历所有段
msg.Stats() 获取消息统计信息
seg.Repetitions(fieldIdx) 获取字段的所有重复值
seg.Components(fieldIdx) 获取字段的所有组件
Generate(msg *Message, opts ...ACKOption) 生成 ACK/NAK 响应
NewValidator(rules ...Rule) 创建消息验证器
NewServer(addr string, handler Handler) 创建 MLLP 服务器
Dial(addr string) 创建 MLLP 客户端
DialTLS(addr string, config) 创建 TLS MLLP 客户端
NewClientPool(addr) 创建 MLLP 客户端连接池
段帮助函数
帮助函数 描述
msg.PID() 获取 PID 段帮助器
msg.MSH() 获取 MSH 段帮助器
msg.PV1() 获取 PV1 段帮助器
msg.OBR() 获取 OBR 段帮助器
msg.OBX() 获取第一个 OBX 段帮助器
msg.AllOBX() 获取所有 OBX 段
msg.NK1() 获取 NK1 段帮助器
msg.DG1() 获取 DG1 段帮助器
许可证

MIT 许可证 - 详见 LICENSE


📚 GoDoc🐛 Issues🌐 HL7 Official

Documentation

Overview

Package hl7 provides types and functions for parsing and building HL7 v2.x healthcare messages.

The package supports multiple parsing modes including struct-based unmarshaling with tags, streaming parsing, and MLLP network transport.

Index

Constants

View Source
const (
	AA    = "AA" // Application Accept
	AE    = "AE" // Application Error
	AR    = "AR" // Application Reject
	CA    = "CA" // Commit Accept (for Enhanced Acknowledgment Mode)
	ACKCE = "CE" // Commit Error (for Enhanced Acknowledgment Mode)
	CR    = "CR" // Commit Reject (for Enhanced Acknowledgment Mode)
)

ACK codes (HL7 v2.x Standard)

View Source
const (
	MLLP_START = 0x0B
	MLLP_END   = 0x1C
	MLLP_CR    = 0x0D
)
View Source
const (
	DefaultMaxMessageSize = 64 * 1024 // 64KB
	DefaultMaxSegments    = 1000
	DefaultMaxFieldLength = 32 * 1024  // 32KB
	DefaultBufferSize     = 256 * 1024 // 256KB for Scanner buffer
)

Default values for Scanner configuration

Variables

View Source
var (
	ErrMessageTooLarge = &ScannerError{Message: "message exceeds maximum size limit"}
	ErrInvalidMLLP     = &ScannerError{Message: "invalid MLLP frame"}
)

Common scanner errors

View Source
var (
	ErrInvalidUTF8 = errors.New("invalid UTF-8 sequence")
	ErrInvalidHL7  = errors.New("invalid HL7 escape sequence")
)
View Source
var HL7Tables = map[string]HL7Table{
	"HL70001": {
		TableID:   "HL70001",
		TableName: "Administrative Sex",
		Values: map[string]string{
			"A": "Ambiguous",
			"F": "Female",
			"M": "Male",
			"N": "Not applicable",
			"O": "Other",
			"U": "Unknown",
		},
	},
	"HL70002": {
		TableID:   "HL70002",
		TableName: "Marital Status",
		Values: map[string]string{
			"A": "Separated",
			"D": "Divorced",
			"I": "Interlocutory",
			"M": "Married",
			"P": "Polygamous",
			"S": "Single",
			"T": "Domestic partner",
			"U": "Unknown",
			"W": "Widowed",
		},
	},
	"HL70004": {
		TableID:   "HL70004",
		TableName: "Patient Class",
		Values: map[string]string{
			"B": "Obstetrics",
			"C": "Commercial Account",
			"E": "Emergency",
			"I": "Invalid",
			"N": "Not Applicable",
			"O": "Outpatient",
			"P": "Preadmit",
			"R": "Recurring patient",
			"U": "Unknown",
		},
	},
	"HL70006": {
		TableID:   "HL70006",
		TableName: "Religion",
		Values: map[string]string{
			"AG":  "Anglican",
			"BAP": "Baptist",
			"BTH": "Buddhist",
			"CAT": "Roman Catholic",
			"CHM": "Christian",
			"CON": "Confucian",
			"DOC": "Doctor of Christianity",
			"E":   "Episcopal",
			"EMC": "Eastern Orthodox",
			"ETH": "Ethiopian Orthodox",
			"F":   "Christian (none of the above)",
			"FR":  "French Reformed",
			"FRE": "Friends",
			"G":   "Greek Orthodox",
			"H":   "Hindu",
			"JE":  "Jewish",
			"L":   "Lutheran",
			"MEN": "Mennonite",
			"MET": "Methodist",
			"MOS": "Mormon",
			"MU":  "Muslim",
			"N":   "None",
			"NON": "Nonreligious",
			"ORT": "Orthodox",
			"P":   "Presbyterian",
			"PA":  "Pagan",
			"PRC": "Other Christian",
			"PRO": "Protestant",
			"RE":  "Reformed",
			"REC": "Reformed Church",
			"RF":  "Reformed",
			"S":   "Spiritist",
			"SAL": "Salvation Army",
			"SAM": "Seventh Adventist",
			"SD":  "Seventh Day Adventist",
			"SE":  "Sikh",
			"SH":  "Shintoist",
			"STA": "Storefront",
			"TY":  "Taoist",
			"U":   "Unknown",
			"UNC": "Unchurched",
			"UNF": "Unitarian",
			"VAR": "Unknown",
			"W":   "Wesleyan",
			"WEL": "Welsh",
			"Z":   "Zoroastrian",
		},
	},
	"HL70038": {
		TableID:   "HL70038",
		TableName: "Order Status",
		Values: map[string]string{
			"A":  "Some, but not all, results available",
			"CA": "Order was canceled",
			"CM": "Order is completed",
			"DC": "Order was discontinued",
			"ER": "Error, order cannot be processed",
			"HD": "Order is on hold",
			"IP": "In process",
			"RP": "Order has been replaced",
			"SC": "Order is scheduled",
		},
	},
	"HL70123": {
		TableID:   "HL70123",
		TableName: "Observation Result Status",
		Values: map[string]string{
			"C": "Record coming over is a correction and thus replaces a final result",
			"D": "Deletes the OBX record",
			"F": "Final result; can only be changed with a corrected result",
			"I": "Specimen in instrument; processing",
			"N": "Not asked; used to indicate no result was considered for this order",
			"O": "Order detail description only (no result)",
			"P": "Preliminary: a result that has been verified",
			"R": "Requested: result is not yet available",
			"S": "Partial: a preliminary result that is currently being processed",
			"U": "Results status not available",
			"W": "Post original as wrong",
			"X": "No results available; order was canceled",
		},
	},
	"HL70125": {
		TableID:   "HL70125",
		TableName: "Value Type",
		Values: map[string]string{
			"AD":   "Address",
			"CE":   "Coded Entry",
			"CF":   "Coded Element With Formatted Values",
			"CK":   "Composite ID With Check Digit",
			"CN":   "Composite ID And Name",
			"CNE":  "Coded With No Exceptions",
			"CNP":  "Coded With No Person Name",
			"CP":   "Composite Price",
			"CPN":  "Composite Person Name",
			"CS":   "Coded Simple Value",
			"CT":   "Coded Token",
			"CX":   "Extended Composite ID With Check Digit",
			"DD":   "Structured Numeric",
			"DLN":  "Driver's License Number",
			"DLT":  "Delta",
			"DR":   "Date/Time Range",
			"DT":   "Date",
			"ED":   "Encapsulated Data",
			"EI":   "Entity Identifier",
			"ELM":  "Encapsulated Data",
			"EN":   "Entity Name",
			"ERN":  "Entity Name",
			"FC":   "Financial Class",
			"FN":   "Family Name",
			"FT":   "Formatted Text",
			"FX":   "Fraction",
			"GTS":  "General Timing Specification",
			"HD":   "Hierarchic Designation",
			"HED":  "HL7 Encapsulated Data",
			"HI":   "Hierarchic Interface",
			"ICD":  "Insurance",
			"ID":   "Coded Value For HL7 Defined Tables",
			"IE":   "Identifier Expressive",
			"IIM":  "Inverse Identifier With Mandatory",
			"IL":   "Instance Identifier",
			"IS":   "Coded Value For User-Defined Tables",
			"JCC":  "Job Code Class",
			"LA":   "Location Address (using Street Address Line)",
			"LA1":  "Location Address",
			"LAH":  "Location Address",
			"LD":   "Location With Address",
			"LI":   "Long Integers",
			"LN":   "License Number",
			"LP":   "Location With Point Of Coordinates",
			"MC":   "Money",
			"MD":   "Multiple Types",
			"MF":   "Money And Percentage",
			"MOC":  "Charge Rate And Time",
			"MO":   "Money",
			"MOP":  "Money Or Percentage",
			"MSA":  "Message Acknowledgment",
			"MSG":  "Message Type",
			"NA":   "Numeric Array",
			"ND":   "Numeric With Decimal",
			"NI":   "National Identifier",
			"NM":   "Numeric",
			"NM1":  "Numeric",
			"NPI":  "National Provider Identifier",
			"NT":   "Numeric Token",
			"NU":   "Numeric",
			"OBR":  "Observation Request",
			"OD":   "Other Numeric",
			"OS":   "Other Scalar",
			"OUI":  "Operator Universal Identifier",
			"OW":   "Order Number And Date",
			"PN":   "Person Name",
			"PPN":  "Performing Person Name",
			"PR":   "Priority",
			"PRA":  "Practitioner ID",
			"PT":   "Processing Type",
			"PTA":  "Payment Type",
			"QIP":  "Query Input Parameter List",
			"QSC":  "Query Selection Criteria",
			"RCD":  "Row Column Definition",
			"RC":   "Regional Center Code",
			"RFR":  "Reference Range",
			"RI":   "Interval",
			"RMC":  "Room Coverage",
			"RP":   "Reference Pointer",
			"RPL":  "Reference Pointer To Location",
			"RP1":  "Referral Information",
			"RP2":  "Referral Information",
			"RP3":  "Referral Information",
			"RP5":  "Referral Information",
			"RPO":  "Referral And Order",
			"RNA":  "Rest Numeric Array",
			"RND":  "Rest Numeric",
			"SNM":  "String Of Name",
			"SN":   "Structured Numeric",
			"SN1":  "Structured Numeric",
			"SPD":  "Specialty",
			"SPS":  "Specimen Source",
			"ST":   "String Data",
			"ST1":  "String Data",
			"TM":   "Time",
			"TN":   "Telephone Number",
			"TQ":   "Timing Quantity",
			"TS":   "Time Stamp",
			"TX":   "Text Data",
			"UC":   "Urgency Classification",
			"UD":   "Undefined",
			"UI":   "Unique Identifier",
			"UID":  "Unique Identifier",
			"UPIN": "UPIN",
			"URI":  "Universal Resource Identifier",
			"UV":   "Undefined Variable",
			"V24":  "Value",
			"VAR":  "Variance",
			"VH":   "Verifying Healthcare Interest",
			"VID":  "Version Identifier",
			"VR":   "Value Range",
			"VT":   "Virtual Table",
			"WCD":  "Wrong Check Digit",
			"XAD":  "Extended Address",
			"XCN":  "Extended Composite ID Number And Name For Persons",
			"XON":  "Extended Composite Name And Identification Number For Organizations",
			"XPN":  "Extended Person Name",
			"XT":   "Text",
			"XTN":  "Extended Telecommunications Number",
		},
	},
	"HL70305": {
		TableID:   "HL70305",
		TableName: "Diagnosis Coding Method",
		Values: map[string]string{
			"01": "ICD-9",
			"02": "ICD-10",
			"99": "Other",
		},
	},
	"HL70394": {
		TableID:   "HL70394",
		TableName: "Message Error Condition Codes",
		Values: map[string]string{
			"0":   "Message accepted",
			"100": "Segment sequence error",
			"101": "Required field missing",
			"102": "Data type error",
			"103": "Table value not found",
			"104": "Unsupported message type",
			"105": "Unsupported event code",
			"106": "Unsupported processing ID",
			"107": "Unsupported version ID",
			"108": "Unknown key identifier",
			"109": "Duplicate key identifier",
			"110": "Application record error",
			"111": "Field content error",
			"112": "Segmentation error",
			"200": "Unsupported character set",
			"207": "Application internal error",
		},
	},
}
View Source
var MessageStructures = map[string]MessageStructure{
	"ADT_A01": {
		MessageType: "ADT^A01",
		Segments: []SegmentRequirement{
			{Name: "MSH", Position: 1, IsRequired: true},
			{Name: "SFT", Position: 2, IsRequired: false},
			{Name: "EVN", Position: 3, IsRequired: true},
			{Name: "PID", Position: 4, IsRequired: true},
			{Name: "PD1", Position: 5, IsRequired: false},
			{Name: "ROL", Position: 6, IsRequired: false},
			{Name: "NK1", Position: 7, IsRequired: false, MaxOccurrence: -1},
			{Name: "PV1", Position: 8, IsRequired: true},
			{Name: "PV2", Position: 9, IsRequired: false},
			{Name: "ROL", Position: 10, IsRequired: false},
			{Name: "DB1", Position: 11, IsRequired: false},
			{Name: "OBX", Position: 12, IsRequired: false, MaxOccurrence: -1},
			{Name: "AL1", Position: 13, IsRequired: false, MaxOccurrence: -1},
			{Name: "DG1", Position: 14, IsRequired: false, MaxOccurrence: -1},
			{Name: "DRG", Position: 15, IsRequired: false},
			{Name: "PR1", Position: 16, IsRequired: false, MaxOccurrence: -1},
			{Name: "GT1", Position: 17, IsRequired: false, MaxOccurrence: -1},
			{Name: "IN1", Position: 18, IsRequired: false, MaxOccurrence: -1},
			{Name: "IN2", Position: 19, IsRequired: false},
			{Name: "IN3", Position: 20, IsRequired: false, MaxOccurrence: -1},
			{Name: "ACC", Position: 21, IsRequired: false},
			{Name: "UB1", Position: 22, IsRequired: false},
			{Name: "UB2", Position: 23, IsRequired: false},
		},
	},
	"ADT_A04": {
		MessageType: "ADT^A04",
		Segments: []SegmentRequirement{
			{Name: "MSH", Position: 1, IsRequired: true},
			{Name: "SFT", Position: 2, IsRequired: false},
			{Name: "EVN", Position: 3, IsRequired: true},
			{Name: "PID", Position: 4, IsRequired: true},
			{Name: "PD1", Position: 5, IsRequired: false},
			{Name: "ROL", Position: 6, IsRequired: false},
			{Name: "NK1", Position: 7, IsRequired: false, MaxOccurrence: -1},
			{Name: "PV1", Position: 8, IsRequired: true},
			{Name: "PV2", Position: 9, IsRequired: false},
			{Name: "ROL", Position: 10, IsRequired: false},
			{Name: "DB1", Position: 11, IsRequired: false},
			{Name: "OBX", Position: 12, IsRequired: false, MaxOccurrence: -1},
			{Name: "AL1", Position: 13, IsRequired: false, MaxOccurrence: -1},
			{Name: "DG1", Position: 14, IsRequired: false, MaxOccurrence: -1},
			{Name: "DRG", Position: 15, IsRequired: false},
		},
	},
	"ORU_R01": {
		MessageType: "ORU^R01",
		Segments: []SegmentRequirement{
			{Name: "MSH", Position: 1, IsRequired: true},
			{Name: "SFT", Position: 2, IsRequired: false},
			{Name: "NTE", Position: 3, IsRequired: false, MaxOccurrence: -1},
			{Name: "PATIENT_RESULT", Position: 4, IsRequired: true, MaxOccurrence: -1},
		},
	},
}
View Source
var SegmentDefinitions = map[string]SegmentDefinition{
	"MSH": {
		Name:          "MSH",
		IsRequired:    true,
		MinOccurrence: 1,
		MaxOccurrence: 1,
		Fields: []FieldDefinition{
			{Index: 1, Name: "FieldSeparator", DataType: "ST", IsRequired: true},
			{Index: 2, Name: "EncodingCharacters", DataType: "ST", IsRequired: true},
			{Index: 3, Name: "SendingApplication", DataType: "HD"},
			{Index: 4, Name: "SendingFacility", DataType: "HD"},
			{Index: 5, Name: "ReceivingApplication", DataType: "HD"},
			{Index: 6, Name: "ReceivingFacility", DataType: "HD"},
			{Index: 7, Name: "DateTimeOfMessage", DataType: "TS"},
			{Index: 8, Name: "Security", DataType: "ST"},
			{Index: 9, Name: "MessageType", DataType: "MSG", IsRequired: true},
			{Index: 10, Name: "MessageControlID", DataType: "ST"},
			{Index: 11, Name: "ProcessingID", DataType: "PT"},
			{Index: 12, Name: "VersionID", DataType: "VID"},
			{Index: 13, Name: "SequenceNumber", DataType: "NM"},
			{Index: 14, Name: "ContinuationPointer", DataType: "ST"},
			{Index: 15, Name: "AcceptAcknowledgmentType", DataType: "ID", Table: "HL70015"},
			{Index: 16, Name: "ApplicationAcknowledgmentType", DataType: "ID", Table: "HL70015"},
			{Index: 17, Name: "CountryCode", DataType: "ID", Table: "HL70039"},
		},
	},
	"PID": {
		Name:          "PID",
		IsRequired:    true,
		MinOccurrence: 1,
		MaxOccurrence: 1,
		Fields: []FieldDefinition{
			{Index: 1, Name: "SetID", DataType: "SI"},
			{Index: 2, Name: "PatientID", DataType: "CX"},
			{Index: 3, Name: "PatientIdentifierList", DataType: "CX", IsRequired: true, MaxLength: 20},
			{Index: 4, Name: "AlternatePatientID", DataType: "CX"},
			{Index: 5, Name: "PatientName", DataType: "XPN", IsRequired: true, Components: []FieldDefinition{
				{Index: 1, Name: "FamilyName", DataType: "FN"},
				{Index: 2, Name: "GivenName", DataType: "ST"},
				{Index: 3, Name: "SecondAndFurtherGivenNames", DataType: "ST"},
				{Index: 4, Name: "Suffix", DataType: "ST"},
				{Index: 5, Name: "Prefix", DataType: "ST"},
				{Index: 6, Name: "Degree", DataType: "ST"},
			}},
			{Index: 6, Name: "MothersMaidenName", DataType: "XPN"},
			{Index: 7, Name: "DateOfBirth", DataType: "TS"},
			{Index: 8, Name: "Sex", DataType: "ID", IsRequired: true, Table: "HL70001"},
			{Index: 9, Name: "PatientAlias", DataType: "XPN"},
			{Index: 10, Name: "Race", DataType: "CE", Table: "HL70005"},
			{Index: 11, Name: "PatientAddress", DataType: "XAD", Components: []FieldDefinition{
				{Index: 1, Name: "StreetAddress", DataType: "ST"},
				{Index: 2, Name: "OtherDesignation", DataType: "ST"},
				{Index: 3, Name: "City", DataType: "ST"},
				{Index: 4, Name: "StateOrProvince", DataType: "ST"},
				{Index: 5, Name: "ZipOrPostalCode", DataType: "ST"},
				{Index: 6, Name: "Country", DataType: "ID", Table: "HL70003"},
				{Index: 7, Name: "AddressType", DataType: "ID", Table: "HL70190"},
			}},
			{Index: 12, Name: "CountyCode", DataType: "ID", Table: "HL70179"},
			{Index: 13, Name: "PhoneHome", DataType: "XTN"},
			{Index: 14, Name: "PhoneBusiness", DataType: "XTN"},
			{Index: 15, Name: "PrimaryLanguage", DataType: "CE", Table: "HL70296"},
			{Index: 16, Name: "MaritalStatus", DataType: "CE", Table: "HL70002"},
			{Index: 17, Name: "Religion", DataType: "CE", Table: "HL70006"},
			{Index: 18, Name: "PatientAccountNumber", DataType: "CX"},
			{Index: 19, Name: "SSN", DataType: "ST"},
			{Index: 20, Name: "DriversLicense", DataType: "DLN"},
			{Index: 21, Name: "BirthPlace", DataType: "ST"},
			{Index: 22, Name: "MultipleBirthIndicator", DataType: "ID", Table: "HL70136"},
			{Index: 23, Name: "BirthOrder", DataType: "NM"},
			{Index: 24, Name: "Citizenship", DataType: "CE", Table: "HL70171"},
			{Index: 25, Name: "VeteransMilitaryStatus", DataType: "CE", Table: "HL70002"},
			{Index: 26, Name: "Nationality", DataType: "CE", Table: "HL70212"},
			{Index: 27, Name: "PatientDeathDateTime", DataType: "TS"},
			{Index: 28, Name: "PatientDeathIndicator", DataType: "ID", Table: "HL70136"},
		},
	},
	"PV1": {
		Name:          "PV1",
		IsRequired:    true,
		MinOccurrence: 1,
		MaxOccurrence: 1,
		Fields: []FieldDefinition{
			{Index: 1, Name: "SetID", DataType: "SI"},
			{Index: 2, Name: "PatientClass", DataType: "ID", IsRequired: true, Table: "HL70004"},
			{Index: 3, Name: "AssignedPatientLocation", DataType: "PL", Components: []FieldDefinition{
				{Index: 1, Name: "PointOfCare", DataType: "ST"},
				{Index: 2, Name: "Room", DataType: "ST"},
				{Index: 3, Name: "Bed", DataType: "ST"},
				{Index: 4, Name: "Facility", DataType: "HD"},
				{Index: 5, Name: "LocationStatus", DataType: "ST"},
				{Index: 6, Name: "PersonLocationType", DataType: "ST"},
			}},
			{Index: 4, Name: "AdmissionType", DataType: "ID", Table: "HL70007"},
			{Index: 5, Name: "PreadmitNumber", DataType: "CX"},
			{Index: 6, Name: "PriorPatientLocation", DataType: "PL"},
			{Index: 7, Name: "AttendingDoctor", DataType: "XCN", Components: []FieldDefinition{
				{Index: 1, Name: "IDNumber", DataType: "ST"},
				{Index: 2, Name: "FamilyName", DataType: "FN"},
				{Index: 3, Name: "GivenName", DataType: "ST"},
			}},
			{Index: 8, Name: "ReferringDoctor", DataType: "XCN"},
			{Index: 9, Name: "ConsultingDoctor", DataType: "XCN"},
			{Index: 10, Name: "HospitalService", DataType: "TS"},
			{Index: 11, Name: "TemporaryLocation", DataType: "PL"},
			{Index: 12, Name: "PreadmitTestIndicator", DataType: "ID", Table: "HL70087"},
			{Index: 13, Name: "ReAdmissionIndicator", DataType: "ID", Table: "HL70112"},
			{Index: 14, Name: "AdmitSource", DataType: "ID", Table: "HL70023"},
			{Index: 15, Name: "AmbulatoryStatus", DataType: "IS", Table: "HL70009"},
			{Index: 16, Name: "VIPIndicator", DataType: "ID", Table: "HL70036"},
			{Index: 17, Name: "AdmittingDoctor", DataType: "XCN"},
			{Index: 18, Name: "PatientType", DataType: "ID", Table: "HL70018"},
			{Index: 19, Name: "VisitNumber", DataType: "CX"},
			{Index: 20, Name: "FinancialClass", DataType: "FC"},
			{Index: 44, Name: "AdmitDateTime", DataType: "TS"},
			{Index: 45, Name: "DischargeDateTime", DataType: "TS"},
		},
	},
	"OBR": {
		Name:          "OBR",
		IsRequired:    false,
		MinOccurrence: 0,
		MaxOccurrence: -1,
		Fields: []FieldDefinition{
			{Index: 1, Name: "SetID", DataType: "SI"},
			{Index: 2, Name: "PlacerOrderNumber", DataType: "EI"},
			{Index: 3, Name: "FillerOrderNumber", DataType: "EI"},
			{Index: 4, Name: "UniversalServiceID", DataType: "CE", IsRequired: true},
			{Index: 5, Name: "Priority", DataType: "ID"},
			{Index: 6, Name: "RequestedDateTime", DataType: "TS"},
			{Index: 7, Name: "ObservationDateTime", DataType: "TS"},
			{Index: 8, Name: "ObservationEndDateTime", DataType: "TS"},
			{Index: 9, Name: "CollectionVolume", DataType: "CQ"},
			{Index: 10, Name: "CollectorIdentifier", DataType: "XCN"},
			{Index: 11, Name: "SpecimenActionCode", DataType: "ID", Table: "HL70065"},
			{Index: 12, Name: "DangerCode", DataType: "CE"},
			{Index: 13, Name: "RelevantClinicalInfo", DataType: "ST"},
			{Index: 14, Name: "SpecimenReceivedDateTime", DataType: "TS"},
			{Index: 15, Name: "SpecimenSource", DataType: "SPS"},
			{Index: 16, Name: "OrderingProvider", DataType: "XCN"},
			{Index: 17, Name: "OrderCallbackPhoneNumber", DataType: "XTN"},
			{Index: 18, Name: "PlacerField1", DataType: "ST"},
			{Index: 19, Name: "PlacerField2", DataType: "ST"},
			{Index: 20, Name: "FillerField1", DataType: "ST"},
			{Index: 21, Name: "FillerField2", DataType: "ST"},
			{Index: 22, Name: "ResultsRptStatusChangeDateTime", DataType: "TS"},
			{Index: 23, Name: "ChargeToPractice", DataType: "MOC"},
			{Index: 24, Name: "DiagnosticServSectionID", DataType: "ID", Table: "HL70074"},
			{Index: 25, Name: "ResultStatus", DataType: "ID", Table: "HL70123"},
			{Index: 26, Name: "ParentResult", DataType: "PRL"},
			{Index: 27, Name: "QuantityTiming", DataType: "TQ"},
			{Index: 28, Name: "ResultCopiesTo", DataType: "XCN"},
			{Index: 29, Name: "Parent", DataType: "EIP"},
			{Index: 30, Name: "TransportationMode", DataType: "ID", Table: "HL70124"},
			{Index: 31, Name: "ReasonForStudy", DataType: "CE"},
			{Index: 32, Name: "PrincipalResultInterpreter", DataType: "NDL"},
			{Index: 33, Name: "AssistantResultInterpreter", DataType: "NDL"},
			{Index: 34, Name: "Technician", DataType: "NDL"},
			{Index: 35, Name: "Transcriptionist", DataType: "NDL"},
			{Index: 36, Name: "ScheduledDateTime", DataType: "TS"},
			{Index: 37, Name: "NumberOfSampleContainers", DataType: "NM"},
			{Index: 38, Name: "TransportLogisticsOfSample", DataType: "CE"},
			{Index: 39, Name: "CollectorsComment", DataType: "CE"},
			{Index: 40, Name: "TransportArrangementResponsibility", DataType: "CE"},
			{Index: 41, Name: "TransportArranged", DataType: "ID", Table: "HL70224"},
			{Index: 42, Name: "EscortRequired", DataType: "ID", Table: "HL70225"},
			{Index: 43, Name: "PlannedPatientTransportComment", DataType: "CE"},
		},
	},
	"OBX": {
		Name:          "OBX",
		IsRequired:    false,
		MinOccurrence: 0,
		MaxOccurrence: -1,
		Fields: []FieldDefinition{
			{Index: 1, Name: "SetID", DataType: "SI"},
			{Index: 2, Name: "ValueType", DataType: "ID", Table: "HL70125"},
			{Index: 3, Name: "ObservationIdentifier", DataType: "CE", IsRequired: true, Components: []FieldDefinition{
				{Index: 1, Name: "Identifier", DataType: "ST"},
				{Index: 2, Name: "Text", DataType: "ST"},
				{Index: 3, Name: "CodingSystem", DataType: "ST"},
			}},
			{Index: 4, Name: "ObservationSubID", DataType: "ST"},
			{Index: 5, Name: "ObservationValue", DataType: "Varies", IsRequired: true},
			{Index: 6, Name: "Units", DataType: "CE"},
			{Index: 7, Name: "ReferenceRange", DataType: "ST"},
			{Index: 8, Name: "AbnormalFlags", DataType: "ID", Table: "HL70078"},
			{Index: 9, Name: "Probability", DataType: "NM"},
			{Index: 10, Name: "NatureOfAbnormalTest", DataType: "ID", Table: "HL70080"},
			{Index: 11, Name: "ResultStatus", DataType: "ID", Table: "HL70085"},
			{Index: 12, Name: "DateLastObsNormalValue", DataType: "TS"},
			{Index: 13, Name: "UserDefinedAccessChecks", DataType: "ST"},
			{Index: 14, Name: "DateTimeOfObservation", DataType: "TS"},
			{Index: 15, Name: "ProducersID", DataType: "CE"},
			{Index: 16, Name: "ResponsibleObserver", DataType: "XCN"},
			{Index: 17, Name: "ObservationMethod", DataType: "CE"},
			{Index: 18, Name: "EquipmentInstanceIdentifier", DataType: "EI"},
			{Index: 19, Name: "DateTimeOfAnalysis", DataType: "TS"},
			{Index: 20, Name: "Reserved", DataType: "ST"},
			{Index: 21, Name: "Reserved", DataType: "ST"},
			{Index: 22, Name: "Reserved", DataType: "ST"},
			{Index: 23, Name: "PerformingOrganizationName", DataType: "XON"},
			{Index: 24, Name: "PerformingOrganizationAddress", DataType: "XAD"},
			{Index: 25, Name: "PerformingOrganizationMedicalDirector", DataType: "XCN"},
		},
	},
	"NK1": {
		Name:          "NK1",
		IsRequired:    false,
		MinOccurrence: 0,
		MaxOccurrence: -1,
		Fields: []FieldDefinition{
			{Index: 1, Name: "SetID", DataType: "SI"},
			{Index: 2, Name: "Name", DataType: "XPN"},
			{Index: 3, Name: "Relationship", DataType: "CE", Table: "HL70063"},
			{Index: 4, Name: "Address", DataType: "XAD"},
			{Index: 5, Name: "PhoneNumber", DataType: "XTN"},
			{Index: 6, Name: "BusinessPhoneNumber", DataType: "XTN"},
			{Index: 7, Name: "ContactRole", DataType: "CE", Table: "HL70131"},
			{Index: 8, Name: "StartDate", DataType: "TS"},
			{Index: 9, Name: "EndDate", DataType: "TS"},
			{Index: 10, Name: "NextOfKinAddresses", DataType: "XAD"},
			{Index: 11, Name: "NextOfKinPhoneNumbers", DataType: "XTN"},
		},
	},
	"DG1": {
		Name:          "DG1",
		IsRequired:    false,
		MinOccurrence: 0,
		MaxOccurrence: -1,
		Fields: []FieldDefinition{
			{Index: 1, Name: "SetID", DataType: "SI"},
			{Index: 2, Name: "DiagnosisCodingMethod", DataType: "ID", Table: "HL70053"},
			{Index: 3, Name: "DiagnosisCode", DataType: "CE", IsRequired: true, Table: "HL70051"},
			{Index: 4, Name: "DiagnosisDescription", DataType: "ST"},
			{Index: 5, Name: "DiagnosisDateTime", DataType: "TS"},
			{Index: 6, Name: "DiagnosisType", DataType: "ID", IsRequired: true, Table: "HL70052"},
		},
	},
	"AL1": {
		Name:          "AL1",
		IsRequired:    false,
		MinOccurrence: 0,
		MaxOccurrence: -1,
		Fields: []FieldDefinition{
			{Index: 1, Name: "SetID", DataType: "SI"},
			{Index: 2, Name: "AllergenTypeCode", DataType: "CE", Table: "HL70027"},
			{Index: 3, Name: "AllergenCode", DataType: "CE", IsRequired: true},
			{Index: 4, Name: "AllergySeverityCode", DataType: "CE", Table: "HL70028"},
			{Index: 5, Name: "AllergyReactionCode", DataType: "ST"},
			{Index: 6, Name: "IdentificationDate", DataType: "TS"},
		},
	},
	"GT1": {
		Name:          "GT1",
		IsRequired:    false,
		MinOccurrence: 0,
		MaxOccurrence: -1,
		Fields: []FieldDefinition{
			{Index: 1, Name: "SetID", DataType: "SI"},
			{Index: 2, Name: "GuarantorNumber", DataType: "CX"},
			{Index: 3, Name: "GuarantorName", DataType: "XPN", IsRequired: true},
			{Index: 4, Name: "GuarantorSpouseName", DataType: "XPN"},
			{Index: 5, Name: "GuarantorAddress", DataType: "XAD"},
			{Index: 6, Name: "GuarantorHomePhone", DataType: "XTN"},
			{Index: 7, Name: "GuarantorBusinessPhone", DataType: "XTN"},
			{Index: 8, Name: "GuarantorDateOfBirth", DataType: "TS"},
			{Index: 9, Name: "GuarantorSex", DataType: "ID", Table: "HL70001"},
			{Index: 10, Name: "GuarantorType", DataType: "IS", Table: "HL70068"},
			{Index: 11, Name: "GuarantorRelationship", DataType: "CE", Table: "HL70063"},
			{Index: 12, Name: "GuarantorSSN", DataType: "ST"},
			{Index: 13, Name: "GuarantorDateBegin", DataType: "TS"},
			{Index: 14, Name: "GuarantorDateEnd", DataType: "TS"},
			{Index: 15, Name: "GuarantorPriority", DataType: "NM"},
		},
	},
	"IN1": {
		Name:          "IN1",
		IsRequired:    false,
		MinOccurrence: 0,
		MaxOccurrence: -1,
		Fields: []FieldDefinition{
			{Index: 1, Name: "SetID", DataType: "SI"},
			{Index: 2, Name: "InsurancePlanID", DataType: "CE", IsRequired: true},
			{Index: 3, Name: "InsuranceCompanyID", DataType: "CX"},
			{Index: 4, Name: "InsuranceCompanyName", DataType: "XON"},
			{Index: 5, Name: "InsuranceCompanyAddress", DataType: "XAD"},
			{Index: 6, Name: "InsuranceCoContactPerson", DataType: "XPN"},
			{Index: 7, Name: "InsuranceCoPhoneNumber", DataType: "XTN"},
			{Index: 8, Name: "GroupNumber", DataType: "ST"},
			{Index: 9, Name: "GroupName", DataType: "XON"},
			{Index: 10, Name: "PlanEffectiveDate", DataType: "TS"},
			{Index: 11, Name: "PlanExpirationDate", DataType: "TS"},
			{Index: 12, Name: "AuthorizationInformation", DataType: "AUI"},
			{Index: 13, Name: "PlanType", DataType: "IS", Table: "HL70086"},
			{Index: 14, Name: "NameOfInsured", DataType: "XPN"},
			{Index: 15, Name: "InsuredRelationship", DataType: "CE", Table: "HL70063"},
			{Index: 16, Name: "InsuredDateOfBirth", DataType: "TS"},
			{Index: 17, Name: "InsuredAddress", DataType: "XAD"},
			{Index: 18, Name: "AssignmentOfBenefits", DataType: "ID", Table: "HL70135"},
			{Index: 19, Name: "CoordinationOfBenefits", DataType: "ID", Table: "HL70136"},
			{Index: 20, Name: "CoordBenPriority", DataType: "ST"},
			{Index: 21, Name: "NoticeOfAdmissionCode", DataType: "ID", Table: "HL70136"},
			{Index: 22, Name: "NoticeOfAdmissionDate", DataType: "TS"},
			{Index: 23, Name: "ReportOfEligibilityCode", DataType: "ID", Table: "HL70136"},
			{Index: 24, Name: "ReportOfEligibilityDate", DataType: "TS"},
			{Index: 25, Name: "ReleaseInformationCode", DataType: "IS", Table: "HL70093"},
			{Index: 26, Name: "DelayDays", DataType: "ST"},
			{Index: 27, Name: "PlanID", DataType: "CE"},
			{Index: 28, Name: "InvalidReason", DataType: "ID", Table: "HL70143"},
			{Index: 29, Name: "EffectiveDate", DataType: "TS"},
			{Index: 30, Name: "ExpirationDate", DataType: "TS"},
		},
	},
	"NTE": {
		Name:          "NTE",
		IsRequired:    false,
		MinOccurrence: 0,
		MaxOccurrence: -1,
		Fields: []FieldDefinition{
			{Index: 1, Name: "SetID", DataType: "SI"},
			{Index: 2, Name: "SourceOfComment", DataType: "ID", Table: "HL70105"},
			{Index: 3, Name: "Comment", DataType: "FT", MaxLength: 65536},
			{Index: 4, Name: "CommentType", DataType: "CE", Table: "HL70204"},
		},
	},
	"ORC": {
		Name:          "ORC",
		IsRequired:    false,
		MinOccurrence: 0,
		MaxOccurrence: 1,
		Fields: []FieldDefinition{
			{Index: 1, Name: "OrderControl", DataType: "ID", IsRequired: true, Table: "HL70119"},
			{Index: 2, Name: "PlacerOrderNumber", DataType: "EI"},
			{Index: 3, Name: "FillerOrderNumber", DataType: "EI"},
			{Index: 4, Name: "PlacerGroupNumber", DataType: "EI"},
			{Index: 5, Name: "OrderStatus", DataType: "ID", Table: "HL70038"},
			{Index: 6, Name: "ResponseFlag", DataType: "ID", Table: "HL70121"},
			{Index: 7, Name: "QuantityTiming", DataType: "TQ"},
			{Index: 8, Name: "Parent", DataType: "EIP"},
			{Index: 9, Name: "DateTimeOfTransaction", DataType: "TS"},
			{Index: 10, Name: "EnteredBy", DataType: "XCN"},
			{Index: 11, Name: "VerifiedBy", DataType: "XCN"},
			{Index: 12, Name: "OrderingProvider", DataType: "XCN"},
			{Index: 13, Name: "EntererLocation", DataType: "PL"},
			{Index: 14, Name: "CallBackPhoneNumber", DataType: "XTN"},
			{Index: 15, Name: "OrderEffectiveDateTime", DataType: "TS"},
			{Index: 16, Name: "OrderControlCodeReason", DataType: "CE"},
			{Index: 17, Name: "EnteringOrganization", DataType: "CE"},
			{Index: 18, Name: "EnteringDevice", DataType: "CE"},
			{Index: 19, Name: "ActionBy", DataType: "XCN"},
		},
	},
}

Functions

func BuildSegmentBytes added in v0.3.0

func BuildSegmentBytes(name string, fields []string, delims Delimiters) []byte

func BuildSegmentString added in v0.3.0

func BuildSegmentString(name string, fields []string, delims Delimiters) string

func ClearRegexCache added in v0.3.0

func ClearRegexCache()

func ConvertFromUTF8 added in v0.2.2

func ConvertFromUTF8(data []byte, dstEncoding Encoding) ([]byte, error)

func ConvertToUTF8 added in v0.2.2

func ConvertToUTF8(data []byte, srcEncoding Encoding) ([]byte, error)

func DecodeMessage added in v0.2.2

func DecodeMessage(data []byte, enc Encoding) ([]byte, error)

func Encode

func Encode(msg *Message) ([]byte, error)

Encode encodes a Message to a byte slice (package-level function).

func EncodeMessage added in v0.2.2

func EncodeMessage(data []byte, enc Encoding) ([]byte, error)

func EncodeString

func EncodeString(msg *Message) (string, error)

EncodeString encodes a Message to a string (package-level function).

func EncodeWithMLLP

func EncodeWithMLLP(msg *Message) ([]byte, error)

EncodeWithMLLP encodes a Message with MLLP framing.

func Escape added in v0.2.2

func Escape(data string) string

func GetACKCode

func GetACKCode(msg *Message) (string, error)

GetACKCode returns the ACK code from an ACK message.

func GetACKText

func GetACKText(msg *Message) (string, error)

GetACKText returns the text message from an ACK message.

func HasError added in v0.2.0

func HasError(msg *Message) (bool, error)

HasError checks if an ACK message indicates an error condition.

func IsACK

func IsACK(msg *Message) bool

IsACK checks if a message is an ACK message.

func IsAccepted

func IsAccepted(msg *Message) (bool, error)

IsAccepted checks if an ACK message indicates acceptance.

func IsHL7Message

func IsHL7Message(data []byte) bool

IsHL7Message checks if the data appears to be an HL7 message.

func IsRejected added in v0.2.0

func IsRejected(msg *Message) (bool, error)

IsRejected checks if an ACK message indicates rejection.

func LookupTable added in v0.2.2

func LookupTable(tableID, code string) (string, bool)

func Marshal

func Marshal(v interface{}) ([]byte, error)

Marshal marshals a value to HL7 format.

func MarshalMessage

func MarshalMessage(v interface{}, msg *Message) error

MarshalMessage marshals a value into an HL7 Message.

func NormalizeLineEndings added in v0.3.0

func NormalizeLineEndings(data []byte) []byte

func ParseComponent

func ParseComponent(field string, index int) string

ParseComponent extracts a component from a field value.

func ParseComponents added in v0.2.0

func ParseComponents(data string) []string

ParseComponents parses a field string into its components.

func PutMessage added in v0.3.0

func PutMessage(msg *Message)

func RegexCacheSize added in v0.3.0

func RegexCacheSize() int

func SetDefaultEncoding added in v0.2.2

func SetDefaultEncoding(enc Encoding)

func SplitField

func SplitField(value string, separator rune) []string

SplitField splits a field by the given separator.

func SplitMessages

func SplitMessages(data []byte) [][]byte

SplitMessages splits multiple HL7 messages from a byte slice.

func StripMLLP

func StripMLLP(data []byte) []byte

StripMLLP removes MLLP framing from data.

func Unescape added in v0.2.2

func Unescape(data string) (string, error)

func Unmarshal

func Unmarshal(data []byte, v interface{}) error

Unmarshal parses HL7 data and stores the result in the value pointed to by v.

func UnmarshalMessage

func UnmarshalMessage(msg *Message, v interface{}) error

UnmarshalMessage unmarshals a Message into the value pointed to by v.

Types

type ACKOption

type ACKOption func(*ackConfig)

ACKOption configures an ACK message.

func Accept

func Accept() ACKOption

Accept creates an option for accepting a message.

func CommitAccept added in v0.2.0

func CommitAccept() ACKOption

CommitAccept creates an option for a commit accept (Enhanced Acknowledgment).

func CommitError added in v0.2.0

func CommitError(text string) ACKOption

CommitError creates an option for a commit error (Enhanced Acknowledgment).

func CommitReject added in v0.2.0

func CommitReject(text string) ACKOption

CommitReject creates an option for a commit reject (Enhanced Acknowledgment).

func Error

func Error(text string) ACKOption

Error creates an option for an error response.

func Reject

func Reject(text string) ACKOption

Reject creates an option for rejecting a message.

func WithCode added in v0.2.0

func WithCode(code string) ACKOption

WithCode sets a custom ACK code.

func WithERR added in v0.2.0

func WithERR(code, severity, diagnostics, location string) ACKOption

WithERR adds an ERR segment to the ACK message. severity: E (Error), W (Warning), I (Information)

func WithErrorCode

func WithErrorCode(code string) ACKOption

WithErrorCode sets the error code (HL7 Table 0357 or custom).

func WithErrorLocation

func WithErrorLocation(location string) ACKOption

WithErrorLocation sets the error location (e.g., "PID.5").

func WithText

func WithText(text string) ACKOption

WithText sets the acknowledgment text.

func WithValidationError added in v0.2.0

func WithValidationError(err *ValidationError) ACKOption

WithValidationError adds an ERR segment from a ValidationError.

type AnyOfRule added in v0.2.2

type AnyOfRule struct {
	// contains filtered or unexported fields
}

func (*AnyOfRule) Validate added in v0.2.2

func (r *AnyOfRule) Validate(msg *Message) *ValidationError

type CE

type CE struct {
	Identifier    string
	Text          string
	CodingSystem  string
	AltIdentifier string
	AltText       string
	AltCodingSys  string
}

CE (Coded Element) represents an HL7 coded element.

func (CE) MarshalHL7

func (c CE) MarshalHL7() ([]byte, error)

MarshalHL7 marshals the CE to HL7 format.

func (*CE) UnmarshalHL7

func (c *CE) UnmarshalHL7(data []byte) error

UnmarshalHL7 unmarshals an HL7 coded element.

type Client

type Client struct {
	// contains filtered or unexported fields
}

func Dial

func Dial(addr string, opts ...ClientOption) (*Client, error)

func DialTLS added in v0.2.0

func DialTLS(addr string, config *tls.Config, opts ...ClientOption) (*Client, error)

func (*Client) Close

func (c *Client) Close() error

func (*Client) RemoteAddr added in v0.2.2

func (c *Client) RemoteAddr() string

func (*Client) Send

func (c *Client) Send(ctx context.Context, msg *Message) (*Message, error)

func (*Client) SendWithRetry added in v0.2.2

func (c *Client) SendWithRetry(ctx context.Context, msg *Message) (*Message, error)

SendWithRetry sends a message with retry on failure. Uses exponential backoff between retries.

type ClientOption

type ClientOption func(*Client)

func WithDialTimeout

func WithDialTimeout(d time.Duration) ClientOption

func WithOnRetry added in v0.2.2

func WithOnRetry(fn func(attempt int, err error)) ClientOption

func WithRetry added in v0.2.2

func WithRetry(count int, delay time.Duration) ClientOption

func WithRetryWithBackoff added in v0.2.2

func WithRetryWithBackoff(count int, initialDelay time.Duration, maxDelay time.Duration) ClientOption

func WithTLSClient added in v0.2.0

func WithTLSClient(tls bool) ClientOption

type ClientPool added in v0.2.2

type ClientPool struct {
	// contains filtered or unexported fields
}

func NewClientPool added in v0.2.2

func NewClientPool(addr string, opts ...ClientOption) *ClientPool

NewClientPool creates a new client pool for connection reuse.

func (*ClientPool) Close added in v0.2.2

func (p *ClientPool) Close()

Close closes the pool and all client connections.

func (*ClientPool) Get added in v0.2.2

func (p *ClientPool) Get(ctx context.Context) (*Client, error)

Get retrieves a client from the pool, creating a new one if needed.

func (*ClientPool) Put added in v0.2.2

func (p *ClientPool) Put(client *Client)

Put returns a client to the pool for reuse.

func (*ClientPool) Send added in v0.2.2

func (p *ClientPool) Send(ctx context.Context, msg *Message) (*Message, error)

Send sends a message using a pooled client.

func (*ClientPool) SendWithRetry added in v0.2.2

func (p *ClientPool) SendWithRetry(ctx context.Context, msg *Message) (*Message, error)

SendWithRetry sends a message using a pooled client with retry support.

type CodedElement added in v0.2.2

type CodedElement struct {
	Identifier      string `hl7:"1"`
	Text            string `hl7:"2"`
	CodingSystem    string `hl7:"3"`
	AltIdentifier   string `hl7:"4"`
	AltText         string `hl7:"5"`
	AltCodingSystem string `hl7:"6"`
}

type Component added in v0.2.2

type Component struct {
	Time      time.Time
	Timezone  string
	Precision string
}

type CompositeRule added in v0.2.2

type CompositeRule struct {
	// contains filtered or unexported fields
}

func (*CompositeRule) Validate added in v0.2.2

func (r *CompositeRule) Validate(msg *Message) *ValidationError

type DG1Helper added in v0.2.0

type DG1Helper struct {
	// contains filtered or unexported fields
}

func (DG1Helper) DiagnosisCode added in v0.2.0

func (h DG1Helper) DiagnosisCode() string

func (DG1Helper) DiagnosisDateTime added in v0.2.0

func (h DG1Helper) DiagnosisDateTime() string

func (DG1Helper) DiagnosisDescription added in v0.2.0

func (h DG1Helper) DiagnosisDescription() string

func (DG1Helper) DiagnosisType added in v0.2.0

func (h DG1Helper) DiagnosisType() string

func (DG1Helper) Exists added in v0.2.0

func (h DG1Helper) Exists() bool

func (DG1Helper) SetID added in v0.2.0

func (h DG1Helper) SetID() string

type DateFormatRule added in v0.2.2

type DateFormatRule struct {
	// contains filtered or unexported fields
}

func (*DateFormatRule) Validate added in v0.2.2

func (r *DateFormatRule) Validate(msg *Message) *ValidationError

type Decoder added in v0.2.2

type Decoder struct {
	// contains filtered or unexported fields
}

func NewDecoder added in v0.2.2

func NewDecoder() *Decoder

func (*Decoder) Decode added in v0.2.2

func (d *Decoder) Decode(data []byte) ([]byte, error)

func (*Decoder) WithEncoding added in v0.2.2

func (d *Decoder) WithEncoding(enc Encoding) *Decoder

func (*Decoder) WithEscapeHandling added in v0.2.2

func (d *Decoder) WithEscapeHandling(enabled bool) *Decoder

type Delimiters

type Delimiters struct {
	Field        rune
	Component    rune
	Repetition   rune
	Escape       rune
	SubComponent rune
}

Delimiters contains the HL7 delimiter characters.

func DefaultDelimiters

func DefaultDelimiters() Delimiters

DefaultDelimiters returns the default HL7 delimiters.

type ERRInfo added in v0.2.0

type ERRInfo struct {
	ErrorLocation       string
	HL7ErrorCode        string
	HL7ErrorCodeSys     string
	Severity            string
	Diagnostics         string
	UserMessage         string
	HelpLocation        string
	VerboseHelpLocation string
	Expression          string
}

ERRInfo contains information from an ERR segment.

func GetErrors added in v0.2.0

func GetErrors(msg *Message) []ERRInfo

GetErrors returns all ERR segments from an ACK message.

func (ERRInfo) String added in v0.2.0

func (e ERRInfo) String() string

String returns a formatted error string.

type Encoder

type Encoder struct {
	// contains filtered or unexported fields
}

Encoder encodes HL7 messages to byte slices.

func NewEncoder

func NewEncoder() *Encoder

NewEncoder creates a new Encoder with default settings.

func NewEncoderWithDelimiters

func NewEncoderWithDelimiters(delims Delimiters) *Encoder

NewEncoderWithDelimiters creates a new Encoder with custom delimiters.

func (*Encoder) Encode

func (e *Encoder) Encode(msg *Message) ([]byte, error)

Encode encodes a Message to a byte slice.

func (*Encoder) EncodeString

func (e *Encoder) EncodeString(msg *Message) (string, error)

EncodeString encodes a Message to a string.

func (*Encoder) EncodeWithOptions added in v0.2.2

func (e *Encoder) EncodeWithOptions(msg *Message, enc Encoding) ([]byte, error)

func (*Encoder) WithEncoding added in v0.2.2

func (e *Encoder) WithEncoding(enc Encoding) *Encoder

func (*Encoder) WithEscapeHandling added in v0.2.2

func (e *Encoder) WithEscapeHandling(enabled bool) *Encoder

func (*Encoder) WithMLLPFraming

func (e *Encoder) WithMLLPFraming(enabled bool) *Encoder

WithMLLPFraming enables or disables MLLP framing.

type Encoding added in v0.2.2

type Encoding string
const (
	EncodingASCII       Encoding = "ASCII"
	EncodingUTF8        Encoding = "UTF-8"
	EncodingUTF16       Encoding = "UTF-16"
	EncodingUTF16LE     Encoding = "UTF-16LE"
	EncodingUTF16BE     Encoding = "UTF-16BE"
	EncodingISO88591    Encoding = "ISO-8859-1"
	EncodingWindows1252 Encoding = "Windows-1252"
	EncodingLatin1      Encoding = "latin1"
)

func GetDefaultEncoding added in v0.2.2

func GetDefaultEncoding() Encoding

type EscapeHandler added in v0.2.2

type EscapeHandler struct {
	// contains filtered or unexported fields
}

func NewEscapeHandler added in v0.2.2

func NewEscapeHandler() *EscapeHandler

func (*EscapeHandler) Decode added in v0.2.2

func (h *EscapeHandler) Decode(data string) (string, error)

func (*EscapeHandler) Encode added in v0.2.2

func (h *EscapeHandler) Encode(data string) string

type ExtendedAddress added in v0.2.2

type ExtendedAddress struct {
	StreetAddress              string `hl7:"1"`
	OtherDesignation           string `hl7:"2"`
	City                       string `hl7:"3"`
	StateOrProvince            string `hl7:"4"`
	ZipOrPostalCode            string `hl7:"5"`
	Country                    string `hl7:"6"`
	AddressType                string `hl7:"7"`
	OtherGeographicDesignation string `hl7:"8"`
	CountyCode                 string `hl7:"9"`
	AddressRepresentationCode  string `hl7:"10"`
}

type ExtendedCompositeID added in v0.2.2

type ExtendedCompositeID struct {
	IDNumber           string `hl7:"1"`
	CheckDigit         string `hl7:"2"`
	CheckDigitScheme   string `hl7:"3"`
	AssigningAuthority string `hl7:"4"`
	IdentifierTypeCode string `hl7:"5"`
	AssigningFacility  string `hl7:"6"`
	EffectiveDate      string `hl7:"7"`
	ExpirationDate     string `hl7:"8"`
}

type ExtendedPhoneNumber added in v0.2.2

type ExtendedPhoneNumber struct {
	TelephoneNumber          string `hl7:"1"`
	TelecommunicationUseCode string `hl7:"2"`
	EquipmentType            string `hl7:"3"`
	EmailAddress             string `hl7:"4"`
	CountryCode              string `hl7:"5"`
	AreaCityCode             string `hl7:"6"`
	LocalNumber              string `hl7:"7"`
	Extension                string `hl7:"8"`
	Text                     string `hl7:"9"`
}

type Field added in v0.2.0

type Field struct {
	Value      string
	Components []string
}

Field represents a parsed HL7 field.

func ParseField added in v0.2.0

func ParseField(data string) Field

ParseField parses a field string into a Field struct with components.

type FieldDefinition added in v0.2.2

type FieldDefinition struct {
	Index      int
	Name       string
	DataType   string
	IsRequired bool
	MaxLength  int
	Table      string
	Components []FieldDefinition
}

func GetFieldDefinition added in v0.2.2

func GetFieldDefinition(segmentName string, fieldIndex int) (FieldDefinition, bool)

type FieldError

type FieldError struct {
	Segment string
	Field   int
	Err     error
	Value   string
}

FieldError represents an error related to a specific field.

func (*FieldError) Error

func (e *FieldError) Error() string

Error implements the error interface.

func (*FieldError) Unwrap

func (e *FieldError) Unwrap() error

Unwrap returns the underlying error.

type HL7Table added in v0.2.2

type HL7Table struct {
	TableID   string
	TableName string
	Values    map[string]string
}

type Handler

type Handler func(ctx context.Context, msg *Message) (*Message, error)

type ID

type ID struct {
	Value string
}

ID (Identifier) represents an HL7 identifier.

func (ID) MarshalHL7

func (i ID) MarshalHL7() ([]byte, error)

MarshalHL7 marshals the ID to HL7 format.

func (ID) String

func (i ID) String() string

String returns the string representation of the ID.

func (*ID) UnmarshalHL7

func (i *ID) UnmarshalHL7(data []byte) error

UnmarshalHL7 unmarshals an HL7 identifier.

type Location added in v0.2.2

type Location struct {
	Segment      string
	SegmentIndex int // 0 means first/none
	Field        int
	Component    int
	SubComponent int
	Repetition   int // For repeated fields within a segment
}

Location represents a parsed HL7 location string.

func ParseLocation added in v0.2.2

func ParseLocation(location string) (*Location, error)

ParseLocation parses a location string into a Location struct. Supports formats:

  • "PID" -> segment only
  • "PID.3" -> segment.field
  • "PID.3.1" -> segment.field.component
  • "PID.3.1.2" -> segment.field.component.subcomponent
  • "PID[1]" -> first PID segment
  • "PID[2].3" -> second PID segment, field 3
  • "PID.3[0]" -> first repetition of field 3
  • "PID.3[1].1" -> second repetition of field 3, component 1

type MSHHelper added in v0.2.0

type MSHHelper struct {
	// contains filtered or unexported fields
}

func (MSHHelper) AcceptAcknowledgmentType added in v0.2.0

func (h MSHHelper) AcceptAcknowledgmentType() string

func (MSHHelper) ApplicationAcknowledgmentType added in v0.2.0

func (h MSHHelper) ApplicationAcknowledgmentType() string

func (MSHHelper) ContinuationPointer added in v0.2.0

func (h MSHHelper) ContinuationPointer() string

func (MSHHelper) CountryCode added in v0.2.0

func (h MSHHelper) CountryCode() string

func (MSHHelper) DateTime added in v0.2.0

func (h MSHHelper) DateTime() time.Time

func (MSHHelper) DateTimeOfMessage added in v0.2.0

func (h MSHHelper) DateTimeOfMessage() string

func (MSHHelper) EncodingCharacters added in v0.2.0

func (h MSHHelper) EncodingCharacters() string

func (MSHHelper) Exists added in v0.2.0

func (h MSHHelper) Exists() bool

func (MSHHelper) FieldSeparator added in v0.2.0

func (h MSHHelper) FieldSeparator() string

func (MSHHelper) MessageControlID added in v0.2.0

func (h MSHHelper) MessageControlID() string

func (MSHHelper) MessageType added in v0.2.0

func (h MSHHelper) MessageType() string

func (MSHHelper) MessageTypeCode added in v0.2.0

func (h MSHHelper) MessageTypeCode() string

func (MSHHelper) MessageTypeStructure added in v0.2.0

func (h MSHHelper) MessageTypeStructure() string

func (MSHHelper) MessageTypeTrigger added in v0.2.0

func (h MSHHelper) MessageTypeTrigger() string

func (MSHHelper) ProcessingID added in v0.2.0

func (h MSHHelper) ProcessingID() string

func (MSHHelper) ReceivingApplication added in v0.2.0

func (h MSHHelper) ReceivingApplication() string

func (MSHHelper) ReceivingFacility added in v0.2.0

func (h MSHHelper) ReceivingFacility() string

func (MSHHelper) Security added in v0.2.0

func (h MSHHelper) Security() string

func (MSHHelper) SendingApplication added in v0.2.0

func (h MSHHelper) SendingApplication() string

func (MSHHelper) SendingFacility added in v0.2.0

func (h MSHHelper) SendingFacility() string

func (MSHHelper) SequenceNumber added in v0.2.0

func (h MSHHelper) SequenceNumber() string

func (MSHHelper) VersionID added in v0.2.0

func (h MSHHelper) VersionID() string

type Marshaler

type Marshaler interface {
	MarshalHL7() ([]byte, error)
}

Marshaler is the interface implemented by types that can marshal themselves into HL7.

type Message

type Message struct {
	// contains filtered or unexported fields
}

Message represents an HL7 v2.x message containing multiple segments.

func DialAndSend

func DialAndSend(ctx context.Context, addr string, msg *Message, opts ...ClientOption) (*Message, error)

func DialAndSendTLS added in v0.2.0

func DialAndSendTLS(ctx context.Context, addr string, msg *Message, config *tls.Config, opts ...ClientOption) (*Message, error)

func Generate

func Generate(original *Message, options ...ACKOption) (*Message, error)

Generate generates an ACK message in response to the given message.

func GenerateACK

func GenerateACK(original *Message, options ...ACKOption) (*Message, error)

GenerateACK is an alias for Generate.

func GenerateACKWithValidation added in v0.2.0

func GenerateACKWithValidation(original *Message, errors []*ValidationError) (*Message, error)

GenerateACKWithValidation generates an ACK with multiple validation errors.

func GetMessage added in v0.3.0

func GetMessage() *Message

func NewMessage

func NewMessage() *Message

NewMessage creates a new empty Message.

func Parse

func Parse(data []byte) (*Message, error)

Parse parses raw HL7 data into a Message (package-level function).

func ParseParallel added in v0.3.0

func ParseParallel(ctx context.Context, data []byte) (*Message, error)

func ParseParallelWithWorkers added in v0.3.0

func ParseParallelWithWorkers(ctx context.Context, data []byte, workers, threshold int) (*Message, error)

func ParseString

func ParseString(data string) (*Message, error)

ParseString parses an HL7 message from a string.

func (*Message) AddSegment

func (m *Message) AddSegment(seg Segment)

AddSegment adds a segment to the message.

func (*Message) AllDG1 added in v0.2.0

func (m *Message) AllDG1() []DG1Helper

func (*Message) AllNK1 added in v0.2.0

func (m *Message) AllNK1() []NK1Helper

func (*Message) AllOBR added in v0.2.0

func (m *Message) AllOBR() []OBRHelper

func (*Message) AllOBX added in v0.2.0

func (m *Message) AllOBX() []OBXHelper

func (*Message) AllSegments

func (m *Message) AllSegments() []Segment

AllSegments returns all segments in the message.

func (*Message) ControlID

func (m *Message) ControlID() string

ControlID returns the message control ID.

func (*Message) CountSegment added in v0.2.2

func (m *Message) CountSegment(name string) int

CountSegment returns the count of segments with the given name.

func (*Message) DG1 added in v0.2.0

func (m *Message) DG1() DG1Helper

func (*Message) Get added in v0.2.0

func (m *Message) Get(location string) (string, error)

Get retrieves a field value by location string. Location format: "SEGMENT.FIELD" or "SEGMENT.FIELD.COMPONENT" or "SEGMENT.FIELD.COMPONENT.SUBCOMPONENT" For repeated segments, use: "SEGMENT[INDEX].FIELD"

func (*Message) GetAllRepetitions added in v0.2.2

func (m *Message) GetAllRepetitions(location string) ([]string, error)

GetAllRepetitions returns all repetitions of a field value.

func (*Message) GetNthSegment added in v0.2.2

func (m *Message) GetNthSegment(name string, n int) (Segment, bool)

GetNthSegment returns the nth segment (1-based index) with the given name.

func (*Message) HasSegment added in v0.2.2

func (m *Message) HasSegment(name string) bool

HasSegment checks if a segment exists in the message.

func (*Message) Iterate added in v0.2.0

func (m *Message) Iterate() <-chan SegmentIterator

Iterate returns a channel that yields all segments in the message.

func (*Message) MSH added in v0.2.0

func (m *Message) MSH() MSHHelper

func (*Message) MustGet added in v0.2.0

func (m *Message) MustGet(location string) string

MustGet retrieves a field value by location string, panics on error.

func (*Message) NK1 added in v0.2.0

func (m *Message) NK1() NK1Helper

func (*Message) OBR added in v0.2.0

func (m *Message) OBR() OBRHelper

func (*Message) OBX added in v0.2.0

func (m *Message) OBX() OBXHelper

func (*Message) PID added in v0.2.0

func (m *Message) PID() PIDHelper

func (*Message) PV1 added in v0.2.0

func (m *Message) PV1() PV1Helper

func (*Message) Segment

func (m *Message) Segment(name string) (Segment, bool)

Segment returns the first segment with the given name.

func (*Message) Segments

func (m *Message) Segments(name string) []Segment

Segments returns all segments with the given name.

func (*Message) SetSegment

func (m *Message) SetSegment(seg Segment)

SetSegment updates or adds a segment to the message. If a segment with the same name exists, it updates the first occurrence. Otherwise, it adds the segment to the end.

func (*Message) Stats added in v0.2.0

func (m *Message) Stats() MessageStats

Stats returns statistics about the message.

func (*Message) Summary added in v0.2.0

func (m *Message) Summary() string

Summary returns a human-readable summary of the message.

func (*Message) Type

func (m *Message) Type() string

Type returns the message type (e.g., "ADT^A01").

type MessageBuilder added in v0.3.0

type MessageBuilder struct {
	// contains filtered or unexported fields
}

func NewMessageBuilder added in v0.3.0

func NewMessageBuilder() *MessageBuilder

func (*MessageBuilder) AddSegment added in v0.3.0

func (b *MessageBuilder) AddSegment(name string, fields ...string) *MessageBuilder

func (*MessageBuilder) Build added in v0.3.0

func (b *MessageBuilder) Build() *Message

func (*MessageBuilder) Release added in v0.3.0

func (b *MessageBuilder) Release()

func (*MessageBuilder) WithDelimiters added in v0.3.0

func (b *MessageBuilder) WithDelimiters(d Delimiters) *MessageBuilder

type MessageStats added in v0.2.0

type MessageStats struct {
	SegmentCount int
	SegmentTypes map[string]int
	TotalFields  int
	EmptyFields  int
	HasMSH       bool
	HasPID       bool
	HasPV1       bool
	MessageType  string
	Version      string
}

MessageStats contains statistics about a message.

type MessageStructure added in v0.2.2

type MessageStructure struct {
	MessageType string
	Version     string
	Segments    []SegmentRequirement
}

func LookupMessageStructure added in v0.2.2

func LookupMessageStructure(messageType string) (MessageStructure, bool)

type MessageStructureRule added in v0.2.2

type MessageStructureRule struct {
	// contains filtered or unexported fields
}

func (*MessageStructureRule) Validate added in v0.2.2

func (r *MessageStructureRule) Validate(msg *Message) *ValidationError

type MessageTypeRule added in v0.2.2

type MessageTypeRule struct {
	// contains filtered or unexported fields
}

func (*MessageTypeRule) Validate added in v0.2.2

func (r *MessageTypeRule) Validate(msg *Message) *ValidationError

type NK1Helper added in v0.2.0

type NK1Helper struct {
	// contains filtered or unexported fields
}

func (NK1Helper) Address added in v0.2.0

func (h NK1Helper) Address() string

func (NK1Helper) BusinessPhoneNumber added in v0.2.0

func (h NK1Helper) BusinessPhoneNumber() string

func (NK1Helper) ContactRole added in v0.2.0

func (h NK1Helper) ContactRole() string

func (NK1Helper) EndDate added in v0.2.0

func (h NK1Helper) EndDate() string

func (NK1Helper) Exists added in v0.2.0

func (h NK1Helper) Exists() bool

func (NK1Helper) Name added in v0.2.0

func (h NK1Helper) Name() string

func (NK1Helper) PhoneNumber added in v0.2.0

func (h NK1Helper) PhoneNumber() string

func (NK1Helper) Relationship added in v0.2.0

func (h NK1Helper) Relationship() string

func (NK1Helper) SetID added in v0.2.0

func (h NK1Helper) SetID() string

func (NK1Helper) StartDate added in v0.2.0

func (h NK1Helper) StartDate() string

type NM

type NM struct {
	Value float64
}

NM (Numeric) represents an HL7 numeric value.

func (NM) MarshalHL7

func (n NM) MarshalHL7() ([]byte, error)

MarshalHL7 marshals the NM to HL7 format.

func (NM) String

func (n NM) String() string

String returns the string representation of the NM.

func (*NM) UnmarshalHL7

func (n *NM) UnmarshalHL7(data []byte) error

UnmarshalHL7 unmarshals an HL7 numeric value.

type NotRule added in v0.2.2

type NotRule struct {
	// contains filtered or unexported fields
}

func (*NotRule) Validate added in v0.2.2

func (r *NotRule) Validate(msg *Message) *ValidationError

type OBRHelper added in v0.2.0

type OBRHelper struct {
	// contains filtered or unexported fields
}

func (OBRHelper) CollectionVolume added in v0.2.0

func (h OBRHelper) CollectionVolume() string

func (OBRHelper) CollectorIdentifier added in v0.2.0

func (h OBRHelper) CollectorIdentifier() string

func (OBRHelper) DangerCode added in v0.2.0

func (h OBRHelper) DangerCode() string

func (OBRHelper) Exists added in v0.2.0

func (h OBRHelper) Exists() bool

func (OBRHelper) FillerOrderNumber added in v0.2.0

func (h OBRHelper) FillerOrderNumber() string

func (OBRHelper) FillerStatusCode added in v0.2.0

func (h OBRHelper) FillerStatusCode() string

func (OBRHelper) ObservationDateTime added in v0.2.0

func (h OBRHelper) ObservationDateTime() string

func (OBRHelper) ObservationEndDateTime added in v0.2.0

func (h OBRHelper) ObservationEndDateTime() string

func (OBRHelper) OrderCallbackPhoneNumber added in v0.2.0

func (h OBRHelper) OrderCallbackPhoneNumber() string

func (OBRHelper) OrderingProvider added in v0.2.0

func (h OBRHelper) OrderingProvider() string

func (OBRHelper) PlacerOrderNumber added in v0.2.0

func (h OBRHelper) PlacerOrderNumber() string

func (OBRHelper) Priority added in v0.2.0

func (h OBRHelper) Priority() string

func (OBRHelper) ReasonForStudy added in v0.2.0

func (h OBRHelper) ReasonForStudy() string

func (OBRHelper) RelevantClinicalInfo added in v0.2.0

func (h OBRHelper) RelevantClinicalInfo() string

func (OBRHelper) RequestedDateTime added in v0.2.0

func (h OBRHelper) RequestedDateTime() string

func (OBRHelper) ResultsRptStatusChangeDateTime added in v0.2.0

func (h OBRHelper) ResultsRptStatusChangeDateTime() string

func (OBRHelper) ServiceIdentifier added in v0.2.0

func (h OBRHelper) ServiceIdentifier() string

func (OBRHelper) ServiceText added in v0.2.0

func (h OBRHelper) ServiceText() string

func (OBRHelper) SetID added in v0.2.0

func (h OBRHelper) SetID() string

func (OBRHelper) SpecimenActionCode added in v0.2.0

func (h OBRHelper) SpecimenActionCode() string

func (OBRHelper) SpecimenReceivedDateTime added in v0.2.0

func (h OBRHelper) SpecimenReceivedDateTime() string

func (OBRHelper) SpecimenSource added in v0.2.0

func (h OBRHelper) SpecimenSource() string

func (OBRHelper) TransportationMode added in v0.2.0

func (h OBRHelper) TransportationMode() string

func (OBRHelper) UniversalServiceID added in v0.2.0

func (h OBRHelper) UniversalServiceID() string

type OBXHelper added in v0.2.0

type OBXHelper struct {
	// contains filtered or unexported fields
}

func (OBXHelper) AbnormalFlags added in v0.2.0

func (h OBXHelper) AbnormalFlags() []string

func (OBXHelper) Exists added in v0.2.0

func (h OBXHelper) Exists() bool

func (OBXHelper) NatureOfAbnormalTest added in v0.2.0

func (h OBXHelper) NatureOfAbnormalTest() string

func (OBXHelper) ObservationDateTime added in v0.2.0

func (h OBXHelper) ObservationDateTime() string

func (OBXHelper) ObservationIdentifier added in v0.2.0

func (h OBXHelper) ObservationIdentifier() string

func (OBXHelper) ObservationIdentifierCode added in v0.2.0

func (h OBXHelper) ObservationIdentifierCode() string

func (OBXHelper) ObservationIdentifierText added in v0.2.0

func (h OBXHelper) ObservationIdentifierText() string

func (OBXHelper) ObservationMethod added in v0.2.0

func (h OBXHelper) ObservationMethod() string

func (OBXHelper) ObservationSubID added in v0.2.0

func (h OBXHelper) ObservationSubID() string

func (OBXHelper) ObservationValue added in v0.2.0

func (h OBXHelper) ObservationValue() string

func (OBXHelper) Probability added in v0.2.0

func (h OBXHelper) Probability() string

func (OBXHelper) ProducersID added in v0.2.0

func (h OBXHelper) ProducersID() string

func (OBXHelper) ReferenceRange added in v0.2.0

func (h OBXHelper) ReferenceRange() string

func (OBXHelper) ResponsibleObserver added in v0.2.0

func (h OBXHelper) ResponsibleObserver() string

func (OBXHelper) ResultStatus added in v0.2.0

func (h OBXHelper) ResultStatus() string

func (OBXHelper) SetID added in v0.2.0

func (h OBXHelper) SetID() string

func (OBXHelper) Units added in v0.2.0

func (h OBXHelper) Units() string

func (OBXHelper) ValueType added in v0.2.0

func (h OBXHelper) ValueType() string

type PIDHelper added in v0.2.0

type PIDHelper struct {
	// contains filtered or unexported fields
}

func (PIDHelper) AlternatePatientID added in v0.2.0

func (h PIDHelper) AlternatePatientID() string

func (PIDHelper) BirthOrder added in v0.2.0

func (h PIDHelper) BirthOrder() string

func (PIDHelper) BirthPlace added in v0.2.0

func (h PIDHelper) BirthPlace() string

func (PIDHelper) Citizenship added in v0.2.0

func (h PIDHelper) Citizenship() []string

func (PIDHelper) City added in v0.2.0

func (h PIDHelper) City() string

func (PIDHelper) Country added in v0.2.0

func (h PIDHelper) Country() string

func (PIDHelper) DateOfBirth added in v0.2.0

func (h PIDHelper) DateOfBirth() string

func (PIDHelper) DateOfBirthTime added in v0.2.0

func (h PIDHelper) DateOfBirthTime() (time.Time, error)

func (PIDHelper) Degree added in v0.2.0

func (h PIDHelper) Degree() string

func (PIDHelper) DriversLicense added in v0.2.0

func (h PIDHelper) DriversLicense() string

func (PIDHelper) EthnicGroup added in v0.2.0

func (h PIDHelper) EthnicGroup() string

func (PIDHelper) Exists added in v0.2.0

func (h PIDHelper) Exists() bool

func (PIDHelper) FirstName added in v0.2.0

func (h PIDHelper) FirstName() string

func (PIDHelper) Gender added in v0.2.0

func (h PIDHelper) Gender() string

func (PIDHelper) LastName added in v0.2.0

func (h PIDHelper) LastName() string

func (PIDHelper) MaritalStatus added in v0.2.0

func (h PIDHelper) MaritalStatus() string

func (PIDHelper) MiddleName added in v0.2.0

func (h PIDHelper) MiddleName() string

func (PIDHelper) MothersMaidenName added in v0.2.0

func (h PIDHelper) MothersMaidenName() string

func (PIDHelper) MultipleBirthIndicator added in v0.2.0

func (h PIDHelper) MultipleBirthIndicator() string

func (PIDHelper) PatientAddress added in v0.2.0

func (h PIDHelper) PatientAddress() string

func (PIDHelper) PatientAlias added in v0.2.0

func (h PIDHelper) PatientAlias() string

func (PIDHelper) PatientID added in v0.2.0

func (h PIDHelper) PatientID() string

func (PIDHelper) PatientIdentifierList added in v0.2.0

func (h PIDHelper) PatientIdentifierList() []string

func (PIDHelper) PatientName added in v0.2.0

func (h PIDHelper) PatientName() string

func (PIDHelper) PhoneBusiness added in v0.2.0

func (h PIDHelper) PhoneBusiness() string

func (PIDHelper) PhoneHome added in v0.2.0

func (h PIDHelper) PhoneHome() string

func (PIDHelper) PostalCode added in v0.2.0

func (h PIDHelper) PostalCode() string

func (PIDHelper) Prefix added in v0.2.0

func (h PIDHelper) Prefix() string

func (PIDHelper) PrimaryLanguage added in v0.2.0

func (h PIDHelper) PrimaryLanguage() string

func (PIDHelper) Race added in v0.2.0

func (h PIDHelper) Race() string

func (PIDHelper) Religion added in v0.2.0

func (h PIDHelper) Religion() string

func (PIDHelper) SSN added in v0.2.0

func (h PIDHelper) SSN() string

func (PIDHelper) Sex added in v0.2.0

func (h PIDHelper) Sex() string

func (PIDHelper) State added in v0.2.0

func (h PIDHelper) State() string

func (PIDHelper) StreetAddress added in v0.2.0

func (h PIDHelper) StreetAddress() string

func (PIDHelper) StreetName added in v0.2.0

func (h PIDHelper) StreetName() string

func (PIDHelper) Suffix added in v0.2.0

func (h PIDHelper) Suffix() string

func (PIDHelper) VeteransMilitaryStatus added in v0.2.0

func (h PIDHelper) VeteransMilitaryStatus() string

type PV1Helper added in v0.2.0

type PV1Helper struct {
	// contains filtered or unexported fields
}

func (PV1Helper) AdmissionDate added in v0.2.0

func (h PV1Helper) AdmissionDate() string

func (PV1Helper) AdmissionType added in v0.2.0

func (h PV1Helper) AdmissionType() string

func (PV1Helper) AdmitSource added in v0.2.0

func (h PV1Helper) AdmitSource() string

func (PV1Helper) AssignedPatientLocation added in v0.2.0

func (h PV1Helper) AssignedPatientLocation() string

func (PV1Helper) AttendingDoctor added in v0.2.0

func (h PV1Helper) AttendingDoctor() string

func (PV1Helper) AttendingDoctorID added in v0.2.0

func (h PV1Helper) AttendingDoctorID() string

func (PV1Helper) AttendingDoctorName added in v0.2.0

func (h PV1Helper) AttendingDoctorName() string

func (PV1Helper) ConsultingDoctor added in v0.2.0

func (h PV1Helper) ConsultingDoctor() []string

func (PV1Helper) DischargeDate added in v0.2.0

func (h PV1Helper) DischargeDate() string

func (PV1Helper) Exists added in v0.2.0

func (h PV1Helper) Exists() bool

func (PV1Helper) HospitalService added in v0.2.0

func (h PV1Helper) HospitalService() string

func (PV1Helper) LocationBed added in v0.2.0

func (h PV1Helper) LocationBed() string

func (PV1Helper) LocationFacility added in v0.2.0

func (h PV1Helper) LocationFacility() string

func (PV1Helper) LocationPointOfCare added in v0.2.0

func (h PV1Helper) LocationPointOfCare() string

func (PV1Helper) LocationRoom added in v0.2.0

func (h PV1Helper) LocationRoom() string

func (PV1Helper) PatientClass added in v0.2.0

func (h PV1Helper) PatientClass() string

func (PV1Helper) ReferringDoctor added in v0.2.0

func (h PV1Helper) ReferringDoctor() string

func (PV1Helper) SetID added in v0.2.0

func (h PV1Helper) SetID() string

func (PV1Helper) VIPIndicator added in v0.2.0

func (h PV1Helper) VIPIndicator() string

type ParseError

type ParseError struct {
	Field   string
	Message string
}

ParseError represents an error that occurs during HL7 message parsing.

func (*ParseError) Error

func (e *ParseError) Error() string

Error implements the error interface.

type Parser

type Parser struct {
	// contains filtered or unexported fields
}

Parser parses HL7 messages.

func NewParser

func NewParser() *Parser

NewParser creates a new Parser with default settings.

func NewParserWithConfig added in v0.2.0

func NewParserWithConfig(config ParserConfig) *Parser

NewParserWithConfig creates a new Parser with custom configuration.

func NewParserWithDelimiters

func NewParserWithDelimiters(delims Delimiters) *Parser

NewParserWithDelimiters creates a new Parser with custom delimiters.

func (*Parser) Parse

func (p *Parser) Parse(data []byte) (*Message, error)

Parse parses raw HL7 data into a Message.

func (*Parser) ParseParallel added in v0.3.0

func (p *Parser) ParseParallel(ctx context.Context, data []byte) (*Message, error)

func (*Parser) ParseParallelWithWorkers added in v0.3.0

func (p *Parser) ParseParallelWithWorkers(ctx context.Context, data []byte, workers, threshold int) (*Message, error)

type ParserConfig added in v0.2.0

type ParserConfig struct {
	MaxSegments    int // Maximum number of segments allowed
	MaxFieldLength int // Maximum length of a field
}

ParserConfig holds configuration for DoS protection.

type PersonName added in v0.2.2

type PersonName struct {
	FamilyName             string `hl7:"1"`
	GivenName              string `hl7:"2"`
	SecondAndFurtherNames  string `hl7:"3"`
	Suffix                 string `hl7:"4"`
	Prefix                 string `hl7:"5"`
	Degree                 string `hl7:"6"`
	NameTypeCode           string `hl7:"7"`
	NameRepresentationCode string `hl7:"8"`
}

type PoolOption added in v0.2.2

type PoolOption func(*ClientPool)

func WithPoolSize added in v0.2.2

func WithPoolSize(size int) PoolOption

type RangeRule added in v0.2.2

type RangeRule struct {
	// contains filtered or unexported fields
}

func (*RangeRule) Validate added in v0.2.2

func (r *RangeRule) Validate(msg *Message) *ValidationError

type Rule

type Rule interface {
	Validate(msg *Message) *ValidationError
}

Rule represents a validation rule.

func AllOf added in v0.2.2

func AllOf(rules ...Rule) Rule

func AnyOf added in v0.2.2

func AnyOf(rules ...Rule) Rule

func Custom

func Custom(location string, fn func(value string) error) Rule

Custom creates a custom validation rule.

func DateFormat added in v0.2.2

func DateFormat(location, format string) Rule

func ExpectedStructure added in v0.2.2

func ExpectedStructure(messageType string) Rule

func Length

func Length(location string, min, max int) Rule

Length creates a rule that checks the length range of a field.

func MaxLength

func MaxLength(location string, max int) Rule

MaxLength creates a rule that checks the maximum length of a field.

func MinLength

func MinLength(location string, min int) Rule

MinLength creates a rule that checks the minimum length of a field.

func Not added in v0.2.2

func Not(rule Rule) Rule

func OneOf

func OneOf(location string, allowed ...string) Rule

OneOf creates a rule that checks if a field value is one of the allowed values.

func Pattern

func Pattern(location string, pattern string) Rule

Pattern creates a rule that checks if a field matches a regex pattern. The compiled regex is cached globally for performance.

func Range added in v0.2.2

func Range(location string, min, max float64) Rule

func Required

func Required(location string) Rule

Required creates a rule that checks if a field is required.

func RequiredTable added in v0.2.2

func RequiredTable(location, tableID string) Rule

func SupportedMessageType added in v0.2.2

func SupportedMessageType(types ...string) Rule

func SupportedVersion added in v0.2.2

func SupportedVersion(versions ...string) Rule

func Table added in v0.2.2

func Table(location, tableID string) Rule

func Value

func Value(location string, expected string) Rule

Value creates a rule that checks if a field has a specific value.

func When added in v0.2.2

func When(condition func(*Message) bool, rule Rule) Rule

type Scanner

type Scanner struct {
	// contains filtered or unexported fields
}

Scanner scans HL7 messages from a stream.

func NewScanner

func NewScanner(reader io.Reader) *Scanner

NewScanner creates a new Scanner with default configuration.

func NewScannerWithOptions added in v0.2.0

func NewScannerWithOptions(reader io.Reader, opts ...ScannerOption) *Scanner

NewScannerWithOptions creates a new Scanner with custom options.

func (*Scanner) Count added in v0.2.0

func (s *Scanner) Count() int

Count returns the number of messages successfully scanned.

func (*Scanner) Err

func (s *Scanner) Err() error

Err returns the first error encountered by the scanner.

func (*Scanner) Message

func (s *Scanner) Message() *Message

Message returns the current message.

func (*Scanner) Reset added in v0.2.0

func (s *Scanner) Reset(reader io.Reader)

Reset resets the scanner to scan from the beginning.

func (*Scanner) Scan

func (s *Scanner) Scan() bool

Scan advances the scanner to the next message. Returns true if a message was scanned, false at EOF or on error.

type ScannerConfig added in v0.2.0

type ScannerConfig struct {
	MaxMessageSize int        // Maximum message size in bytes
	BufferSize     int        // Scanner buffer size (default: 256KB)
	Delimiters     Delimiters // Custom delimiters
	SkipInvalid    bool       // Skip invalid messages and continue scanning
}

ScannerConfig holds configuration for the Scanner.

type ScannerError added in v0.2.0

type ScannerError struct {
	Message   string
	BytesRead int
	Cause     error
}

ScannerError represents an error during message scanning.

func (*ScannerError) Error added in v0.2.0

func (e *ScannerError) Error() string

Error implements the error interface.

func (*ScannerError) Unwrap added in v0.2.0

func (e *ScannerError) Unwrap() error

Unwrap returns the underlying error.

type ScannerOption added in v0.2.0

type ScannerOption func(*ScannerConfig)

ScannerOption configures a Scanner.

func WithBufferSize added in v0.3.0

func WithBufferSize(size int) ScannerOption

WithBufferSize sets a custom buffer size for the scanner. A larger buffer can improve performance for large messages.

func WithDelimiters added in v0.2.0

func WithDelimiters(d Delimiters) ScannerOption

WithDelimiters sets custom delimiters for parsing.

func WithMaxMessageSize

func WithMaxMessageSize(size int) ScannerOption

WithMaxMessageSize sets the maximum message size for the Scanner. Default is 64KB.

func WithSkipInvalid added in v0.2.0

func WithSkipInvalid(skip bool) ScannerOption

WithSkipInvalid configures the scanner to skip invalid messages. When true, the scanner will continue scanning after encountering a parsing error and report the error via Err() at the end.

type Segment

type Segment struct {
	// contains filtered or unexported fields
}

Segment represents an HL7 segment (e.g., MSH, PID, OBX).

func NewSegment

func NewSegment(name string) Segment

NewSegment creates a new Segment with the given name.

func ParseSegment added in v0.2.0

func ParseSegment(data string) *Segment

ParseSegment parses a segment string into a Segment.

func (Segment) Component

func (s Segment) Component(fieldIndex, componentIndex int) string

Component returns the component at the given index within a field.

func (Segment) ComponentCount added in v0.2.2

func (s Segment) ComponentCount(fieldIndex int) int

ComponentCount returns the number of components in a field.

func (Segment) Components added in v0.2.2

func (s Segment) Components(fieldIndex int) []string

Components returns all components of a field.

func (Segment) Field

func (s Segment) Field(index int) string

Field returns the field at the given index (1-based). For MSH segment, field 1 is the field separator.

func (Segment) FieldCount

func (s Segment) FieldCount() int

FieldCount returns the number of fields in the segment.

func (Segment) Fields

func (s Segment) Fields() []string

Fields returns all fields in the segment.

func (Segment) GetRepetition added in v0.2.2

func (s Segment) GetRepetition(fieldIndex, repetitionIndex int) string

GetRepetition returns a specific repetition of a field by index (1-based).

func (Segment) Name

func (s Segment) Name() string

Name returns the segment name.

func (Segment) RepetitionCount added in v0.2.2

func (s Segment) RepetitionCount(fieldIndex int) int

RepetitionCount returns the number of repetitions for a field.

func (Segment) Repetitions added in v0.2.2

func (s Segment) Repetitions(fieldIndex int) []string

Repetitions returns all repetitions of a field.

func (*Segment) SetField

func (s *Segment) SetField(index int, value string)

SetField sets the field at the given index (1-based). Creates empty fields if necessary.

func (Segment) SubComponent

func (s Segment) SubComponent(fieldIndex, componentIndex, subComponentIndex int) string

SubComponent returns the subcomponent at the given indices.

type SegmentDefinition added in v0.2.2

type SegmentDefinition struct {
	Name          string
	Fields        []FieldDefinition
	IsRequired    bool
	MinOccurrence int
	MaxOccurrence int
}

func LookupSegmentDefinition added in v0.2.2

func LookupSegmentDefinition(segmentName string) (SegmentDefinition, bool)

type SegmentIterator added in v0.2.0

type SegmentIterator struct {
	Name   string
	Index  int
	Fields []string
	// contains filtered or unexported fields
}

SegmentIterator provides iteration over segment fields.

func (*SegmentIterator) Count added in v0.2.0

func (i *SegmentIterator) Count() int

Count returns the number of fields in the segment.

func (*SegmentIterator) Next added in v0.2.0

func (i *SegmentIterator) Next() bool

Next advances to the next field in the segment.

func (*SegmentIterator) Segment added in v0.2.0

func (i *SegmentIterator) Segment() Segment

Segment returns the underlying segment.

func (*SegmentIterator) Value added in v0.2.0

func (i *SegmentIterator) Value() string

Value returns the value of the current field.

func (*SegmentIterator) ValueAt added in v0.2.0

func (i *SegmentIterator) ValueAt(index int) string

ValueAt returns the value at the specified field index.

type SegmentRequirement added in v0.2.2

type SegmentRequirement struct {
	Name          string
	SegmentType   string
	Position      int
	Group         string
	IsRequired    bool
	MaxOccurrence int
}

type Server

type Server struct {
	// contains filtered or unexported fields
}

func NewServer

func NewServer(addr string, handler Handler, opts ...ServerOption) *Server

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() error

func (*Server) ListenAndServeTLS added in v0.2.0

func (s *Server) ListenAndServeTLS(certFile, keyFile string) error

func (*Server) Serve

func (s *Server) Serve(ln net.Listener) error

func (*Server) Stop

func (s *Server) Stop() error

type ServerOption

type ServerOption func(*Server)

func WithInsecureTLS added in v0.2.0

func WithInsecureTLS() ServerOption

func WithReadTimeout

func WithReadTimeout(d time.Duration) ServerOption

func WithServerMaxMessageSize added in v0.2.0

func WithServerMaxMessageSize(size int) ServerOption

func WithTLS added in v0.2.0

func WithTLS(config *tls.Config) ServerOption

func WithWriteTimeout

func WithWriteTimeout(d time.Duration) ServerOption

type TableRule added in v0.2.2

type TableRule struct {
	// contains filtered or unexported fields
}

func (*TableRule) Validate added in v0.2.2

func (r *TableRule) Validate(msg *Message) *ValidationError

type Timestamp

type Timestamp struct {
	time.Time
}

Timestamp represents an HL7 timestamp.

func NewTimestamp

func NewTimestamp(t time.Time) Timestamp

NewTimestamp creates a new Timestamp from a time.Time.

func (Timestamp) MarshalHL7

func (t Timestamp) MarshalHL7() ([]byte, error)

MarshalHL7 marshals the Timestamp to HL7 format.

func (Timestamp) String

func (t Timestamp) String() string

String returns the string representation of the Timestamp.

func (*Timestamp) UnmarshalHL7

func (t *Timestamp) UnmarshalHL7(data []byte) error

UnmarshalHL7 unmarshals an HL7 timestamp string.

type Unmarshaler

type Unmarshaler interface {
	UnmarshalHL7(data []byte) error
}

Unmarshaler is the interface implemented by types that can unmarshal HL7 data.

type ValidationError

type ValidationError struct {
	Location string
	Message  string
}

ValidationError represents a validation error for an HL7 message.

func ValidateWithSchema added in v0.2.2

func ValidateWithSchema(msg *Message, messageType string) []*ValidationError

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error implements the error interface.

type Validator

type Validator struct {
	// contains filtered or unexported fields
}

Validator validates HL7 messages against rules.

func NewValidator

func NewValidator(rules ...Rule) *Validator

NewValidator creates a new Validator.

func (*Validator) AddRule

func (v *Validator) AddRule(rule Rule)

AddRule adds a validation rule.

func (*Validator) Validate

func (v *Validator) Validate(msg *Message) []*ValidationError

Validate validates a message and returns all validation errors.

type VersionRule added in v0.2.2

type VersionRule struct {
	// contains filtered or unexported fields
}

func (*VersionRule) Validate added in v0.2.2

func (r *VersionRule) Validate(msg *Message) *ValidationError

type WhenRule added in v0.2.2

type WhenRule struct {
	// contains filtered or unexported fields
}

func (*WhenRule) Validate added in v0.2.2

func (r *WhenRule) Validate(msg *Message) *ValidationError

type XAD

type XAD struct {
	Street       string
	Other        string
	City         string
	State        string
	ZipCode      string
	Country      string
	AddressType  string
	StartDate    string
	EndDate      string
	AssignmentID string
}

XAD (Extended Address) represents an HL7 extended address.

func (XAD) MarshalHL7

func (a XAD) MarshalHL7() ([]byte, error)

MarshalHL7 marshals the XAD to HL7 format.

func (*XAD) UnmarshalHL7

func (a *XAD) UnmarshalHL7(data []byte) error

UnmarshalHL7 unmarshals an HL7 extended address.

type XPN

type XPN struct {
	FamilyName  string
	GivenName   string
	MiddleName  string
	Suffix      string
	Prefix      string
	Degree      string
	Type        string
	Replication string
}

XPN (Extended Person Name) represents an HL7 extended person name.

func (XPN) FullName

func (x XPN) FullName() string

FullName returns the full name as "GivenName FamilyName".

func (XPN) MarshalHL7

func (x XPN) MarshalHL7() ([]byte, error)

MarshalHL7 marshals the XPN to HL7 format.

func (*XPN) UnmarshalHL7

func (x *XPN) UnmarshalHL7(data []byte) error

UnmarshalHL7 unmarshals an HL7 extended person name.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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