edifact

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 8, 2025 License: MIT Imports: 8 Imported by: 0

README ΒΆ

EDIFACT Processing Library

A comprehensive Go library for parsing, processing, and converting EDIFACT (Electronic Data Interchange for Administration, Commerce and Transport) messages with generic converters and universal EDIFACT readers.

πŸš€ Key Features

πŸ”„ Generic EDIFACT Converter - Main Feature

Convert any EDIFACT message to JSON or structured data without needing specific message type handlers:

converter := edifact.NewConverter()

// Works with ANY EDIFACT message type
jsonData, err := converter.ConvertToJSONString(edifactData)
// Returns generic JSON structure with segments, elements, and components
πŸ“– Universal EDIFACT Reader - Main Feature

Read and parse any EDIFACT message into a generic tree structure:

reader := edifact.NewReader()

// Reads ANY EDIFACT message type into generic Message struct
message, err := reader.ReadString(edifactData)
// Returns structured data with segments, elements, and components
🎯 Additional Capabilities
  • Tokenizer: Tokenize any EDIFACT string into segments, elements, and components
  • Parser: Parse tokens into generic EDIFACT message tree structures
  • Message Handlers: Specific handlers for different message types (IFTMIN, INVOIC, etc.)
  • Dispatcher: Route parsed messages to appropriate handlers
  • Detector: Detect message types from UNH segments
  • Extensible: Easy to add new message type handlers

Installation

go get github.com/looksocial/edifact

Quick Start

Install:

go get github.com/looksocial/edifact
Parse an EDIFACT message
import "github.com/looksocial/edifact"

msg, err := edifact.Parse(edifactString)
if err != nil {
    // handle error
}
fmt.Println(msg.Type) // e.g. "IFTMIN"
Convert to JSON
jsonBytes, err := edifact.ToJSON(edifactString)
if err != nil {
    // handle error
}
fmt.Println(string(jsonBytes))
Get a segment by tag
segment, err := edifact.GetSegment(edifactString, "UNH")
if err != nil {
    // handle error
}
fmt.Println(segment.Elements)
Validate a message
if edifact.IsValid(edifactString) {
    fmt.Println("Valid EDIFACT message!")
} else {
    fmt.Println("Invalid EDIFACT message.")
}
Get message info
info, err := edifact.GetSimpleMessageInfo(edifactString)
if err != nil {
    // handle error
}
fmt.Println(info.String())

πŸ—οΈ Library Structure

edifact/
β”œβ”€β”€ internal/
β”‚   β”œβ”€β”€ tokenizer/           # Tokenize any EDIFACT string
β”‚   β”‚   └── tokenizer.go
β”‚   β”œβ”€β”€ parser/              # Parse tokens into generic EDIFACT message tree
β”‚   β”‚   └── parser.go
β”‚   β”œβ”€β”€ message/             # Message-specific handlers (e.g. IFTMIN, INVOIC)
β”‚   β”‚   β”œβ”€β”€ iftmin.go
β”‚   β”‚   └── invoic.go
β”‚   β”œβ”€β”€ dispatcher/          # Dispatches parsed message to correct handler
β”‚   β”‚   └── router.go
β”‚   └── model/               # Generic segment/element/message structs
β”‚       └── types.go
β”œβ”€β”€ pkg/
β”‚   └── edifact/
β”‚       β”œβ”€β”€ reader.go        # Universal reader - reads ANY EDIFACT message
β”‚       β”œβ”€β”€ convert.go       # Generic converter - converts ANY EDIFACT message
β”‚       └── detect.go        # Detects message type from UNH segment

πŸ“‹ Supported Message Types

🎯 Generic Support

The library can handle ANY EDIFACT message type through its generic converter and reader:

  • Generic Converter: Converts any EDIFACT message to JSON/structured data
  • Universal Reader: Reads any EDIFACT message into generic tree structure
  • Type Detection: Detects message type from UNH segment
πŸ”§ Specific Handlers (Optional)

For enhanced processing, specific handlers are available for:

  • IFTMIN: Transport Instruction
  • INVOIC: Invoice
βž• Adding New Message Types

To add enhanced support for a new message type:

  1. Create a new handler in internal/message/
  2. Implement the MessageHandler interface
  3. Register the handler in the router

Example:

package message

import (
    "github.com/looksocial/edifact/model"
)

type ORDERSHandler struct{}

func NewORDERSHandler() *ORDERSHandler {
    return &ORDERSHandler{}
}

func (h *ORDERSHandler) CanHandle(messageType string) bool {
    return messageType == "ORDERS"
}

func (h *ORDERSHandler) Handle(message *model.Message) (interface{}, error) {
    // Implement ORDERS message processing
    return &ORDERSMessage{}, nil
}

type ORDERSMessage struct {
    // Define your message structure
}

Then register it:

converter := edifact.NewConverter()
converter.RegisterHandler("ORDERS", message.NewORDERSHandler())

πŸ“š API Reference

πŸ”„ Generic Converter - Main API
  • NewConverter() - Create a new generic converter with default configuration
  • NewConverterWithConfig(config) - Create a converter with custom configuration
  • ConvertToJSON(edifactString) - Convert ANY EDIFACT message to JSON bytes
  • ConvertToJSONString(edifactString) - Convert ANY EDIFACT message to JSON string
  • ConvertToStructured(edifactString) - Convert ANY EDIFACT message to structured data
  • GetSupportedMessageTypes() - Get list of supported message types
  • RegisterHandler(messageType, handler) - Register a custom handler for enhanced processing
πŸ“– Universal Reader - Main API
  • NewReader() - Create a new universal reader with default configuration
  • NewReaderWithConfig(config) - Create a reader with custom configuration
  • ReadString(input) - Read and parse ANY EDIFACT string
  • ReadFrom(reader) - Read and parse from an io.Reader
  • ReadSegment(segmentStr) - Read and parse a single segment
πŸ” Detector
  • NewDetector() - Create a new detector with default configuration
  • DetectMessageType(edifactString) - Detect message type
  • DetectMessageVersion(edifactString) - Detect message version
  • DetectMessageInfo(edifactString) - Detect both type and version

πŸ› οΈ Error Handling

The library provides comprehensive error handling with detailed error messages:

message, err := reader.ReadString(edifactData)
if err != nil {
    // Handle parsing errors
    log.Printf("Parsing error: %v", err)
    return
}

πŸ§ͺ Testing

Run the tests:

go test ./...

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ“– Examples

See the edifact-examples repository for comprehensive examples and learning materials:

  • Basic Usage: Simple examples of reading and converting EDIFACT messages
  • Advanced Usage: Custom handlers and adapters
  • Bookings: Real-world example using IFTMBF messages for booking systems

πŸ“š Documentation & Examples Index

πŸ“‹ Core Documentation
πŸ§‘β€πŸ’» Usage Examples
πŸŽ“ Learning Courses
β€’ English Course: Fundamental EDIFACT
β€’ Advanced Course: Production-Ready EDI Systems
β€’ Thai Course: EDIFACT to looksocial/edifact

Note: All examples and learning materials are now hosted in the separate edifact-examples repository for better organization and maintenance.

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

This section is empty.

Functions ΒΆ

func CountSegments ΒΆ

func CountSegments(input string) (int, error)

CountSegments counts the number of segments in an EDIFACT message

func DetectType ΒΆ

func DetectType(input string) (string, error)

DetectType detects the message type from an EDIFACT string

func GetElementValue ΒΆ

func GetElementValue(input, segmentTag string, elementPosition int) (string, error)

GetElementValue gets the value of an element from a specific segment

func GetSegment ΒΆ

func GetSegment(input, tag string) (*model.Segment, error)

GetSegment returns the first segment with the given tag

func GetSegments ΒΆ

func GetSegments(input, tag string) ([]*model.Segment, error)

GetSegments returns all segments with the given tag

func IsValid ΒΆ

func IsValid(input string) bool

IsValid checks if an EDIFACT string is valid

func Parse ΒΆ

func Parse(input string) (*model.Message, error)

Parse parses an EDIFACT string and returns a structured message

func ParseFromReader ΒΆ

func ParseFromReader(reader io.Reader) (*model.Message, error)

ParseFromReader parses EDIFACT data from an io.Reader

func ToJSON ΒΆ

func ToJSON(input string) ([]byte, error)

ToJSON converts an EDIFACT string to JSON

func ToJSONString ΒΆ

func ToJSONString(input string) (string, error)

ToJSONString converts an EDIFACT string to a JSON string

Types ΒΆ

type Converter ΒΆ

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

Converter provides functionality to convert EDIFACT messages to structured formats

func NewConverter ΒΆ

func NewConverter() *Converter

NewConverter creates a new EDIFACT converter with default configuration

func NewConverterWithConfig ΒΆ

func NewConverterWithConfig(config model.EDIFACTConfig) *Converter

NewConverterWithConfig creates a new EDIFACT converter with custom configuration

func (*Converter) ConvertMessageToJSON ΒΆ

func (c *Converter) ConvertMessageToJSON(message *model.Message) ([]byte, error)

ConvertMessageToJSON converts a parsed message to JSON

func (*Converter) ConvertToJSON ΒΆ

func (c *Converter) ConvertToJSON(edifactString string) ([]byte, error)

ConvertToJSON converts an EDIFACT string to JSON

func (*Converter) ConvertToJSONString ΒΆ

func (c *Converter) ConvertToJSONString(edifactString string) (string, error)

ConvertToJSONString converts an EDIFACT string to a JSON string

func (*Converter) ConvertToStructured ΒΆ

func (c *Converter) ConvertToStructured(edifactString string) (interface{}, error)

ConvertToStructured converts an EDIFACT string to structured data

func (*Converter) GetParser ΒΆ

func (c *Converter) GetParser() *parser.Parser

GetParser returns the underlying parser (for advanced usage)

func (*Converter) GetRouter ΒΆ

func (c *Converter) GetRouter() *dispatcher.Router

GetRouter returns the underlying router (for advanced usage)

func (*Converter) GetSupportedMessageTypes ΒΆ

func (c *Converter) GetSupportedMessageTypes() []string

GetSupportedMessageTypes returns a list of supported message types

func (*Converter) HasHandler ΒΆ

func (c *Converter) HasHandler(messageType string) bool

HasHandler checks if a handler exists for the given message type

func (*Converter) RegisterHandler ΒΆ

func (c *Converter) RegisterHandler(messageType string, handler model.MessageHandler)

RegisterHandler registers a custom message handler

type Detector ΒΆ

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

Detector provides functionality to detect EDIFACT message types

func NewDetector ΒΆ

func NewDetector() *Detector

NewDetector creates a new EDIFACT detector with default configuration

func NewDetectorWithConfig ΒΆ

func NewDetectorWithConfig(config model.EDIFACTConfig) *Detector

NewDetectorWithConfig creates a new EDIFACT detector with custom configuration

func (*Detector) DetectMessageInfo ΒΆ

func (d *Detector) DetectMessageInfo(edifactString string) (*MessageInfo, error)

DetectMessageInfo detects both message type and version from an EDIFACT string

func (*Detector) DetectMessageInfoFromMessage ΒΆ

func (d *Detector) DetectMessageInfoFromMessage(message *model.Message) (*MessageInfo, error)

DetectMessageInfoFromMessage detects both message type and version from a parsed message

func (*Detector) DetectMessageType ΒΆ

func (d *Detector) DetectMessageType(edifactString string) (string, error)

DetectMessageType detects the message type from an EDIFACT string

func (*Detector) DetectMessageTypeFromMessage ΒΆ

func (d *Detector) DetectMessageTypeFromMessage(message *model.Message) (string, error)

DetectMessageTypeFromMessage detects the message type from a parsed message

func (*Detector) DetectMessageTypeFromSegment ΒΆ

func (d *Detector) DetectMessageTypeFromSegment(unhSegment string) (string, error)

DetectMessageTypeFromSegment detects the message type from a UNH segment string

func (*Detector) DetectMessageVersion ΒΆ

func (d *Detector) DetectMessageVersion(edifactString string) (string, error)

DetectMessageVersion detects the message version from an EDIFACT string

func (*Detector) DetectMessageVersionFromMessage ΒΆ

func (d *Detector) DetectMessageVersionFromMessage(message *model.Message) (string, error)

DetectMessageVersionFromMessage detects the message version from a parsed message

func (*Detector) GetMessageInfo ΒΆ

func (d *Detector) GetMessageInfo(edifactString string) (*MessageInfo, error)

GetMessageInfo returns detailed information about an EDIFACT message

func (*Detector) IsEDIFACT ΒΆ

func (d *Detector) IsEDIFACT(edifactString string) bool

IsEDIFACT checks if a string is a valid EDIFACT message

func (*Detector) ValidateMessage ΒΆ

func (d *Detector) ValidateMessage(edifactString string) (bool, []string)

ValidateMessage validates an EDIFACT message and returns validation errors

type MessageInfo ΒΆ

type MessageInfo struct {
	Type         string `json:"type"`
	Version      string `json:"version"`
	SegmentCount int    `json:"segment_count"`
}

MessageInfo contains information about an EDIFACT message

func (*MessageInfo) String ΒΆ

func (m *MessageInfo) String() string

String returns a string representation of the message info

type Reader ΒΆ

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

Reader provides functionality to read and parse EDIFACT messages

func NewReader ΒΆ

func NewReader() *Reader

NewReader creates a new EDIFACT reader with default configuration

func NewReaderWithConfig ΒΆ

func NewReaderWithConfig(config model.EDIFACTConfig) *Reader

NewReaderWithConfig creates a new EDIFACT reader with custom configuration

func (*Reader) GetConfig ΒΆ

func (r *Reader) GetConfig() model.EDIFACTConfig

GetConfig returns the current configuration

func (*Reader) GetParser ΒΆ

func (r *Reader) GetParser() *parser.Parser

GetParser returns the underlying parser (for advanced usage)

func (*Reader) ReadFrom ΒΆ

func (r *Reader) ReadFrom(reader io.Reader) (*model.Message, error)

ReadFrom reads and parses EDIFACT data from an io.Reader

func (*Reader) ReadSegment ΒΆ

func (r *Reader) ReadSegment(segmentStr string) (*model.Segment, error)

ReadSegment reads and parses a single EDIFACT segment

func (*Reader) ReadString ΒΆ

func (r *Reader) ReadString(input string) (*model.Message, error)

ReadString reads and parses an EDIFACT string

func (*Reader) SetConfig ΒΆ

func (r *Reader) SetConfig(config model.EDIFACTConfig)

SetConfig updates the configuration and recreates the parser

func (*Reader) ValidateMessage ΒΆ

func (r *Reader) ValidateMessage(message *model.Message) error

ValidateMessage validates a parsed message

type SimpleMessageInfo ΒΆ

type SimpleMessageInfo struct {
	Type         string `json:"type"`
	MessageRef   string `json:"message_ref"`
	SegmentCount int    `json:"segment_count"`
}

SimpleMessageInfo contains basic information about an EDIFACT message

func GetMessageInfo ΒΆ

func GetMessageInfo(input string) (*SimpleMessageInfo, error)

GetMessageInfo returns basic information about an EDIFACT message

func (*SimpleMessageInfo) String ΒΆ

func (m *SimpleMessageInfo) String() string

String returns a string representation of the message info

Jump to

Keyboard shortcuts

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