Documentation for the rdf-go RDF parsing/encoding library
Complete reference documentation for rdf-go.
type Term interface {
Kind() TermKind
String() string
}
Term is the interface that all RDF terms implement.
type TermKind uint8
const (
TermIRI TermKind = iota
TermBlankNode
TermLiteral
TermTriple
)
TermKind identifies the type of an RDF term.
type IRI struct {
Value string
}
IRI represents an RDF IRI (Internationalized Resource Identifier).
Methods:
Kind() TermKind - Returns TermIRIString() string - Returns the IRI valuetype BlankNode struct {
ID string
}
BlankNode represents an RDF blank node.
Methods:
Kind() TermKind - Returns TermBlankNodeString() string - Returns "_:" + IDtype Literal struct {
Lexical string
Datatype IRI
Lang string
}
Literal represents an RDF literal value.
Fields:
Lexical - The lexical form of the literalDatatype - Optional datatype IRILang - Optional language tagMethods:
Kind() TermKind - Returns TermLiteralString() string - Returns formatted literal with datatype or language tagtype TripleTerm struct {
S Term
P IRI
O Term
}
TripleTerm represents an RDF-star quoted triple.
Methods:
Kind() TermKind - Returns TermTripleString() string - Returns formatted quoted tripletype Triple struct {
S Term
P IRI
O Term
}
Triple represents an RDF triple (subject, predicate, object).
Methods:
ToStatement() Statement - Converts triple to a statementToQuad() Quad - Converts triple to a quad in the default graphToQuadInGraph(graph Term) Quad - Converts triple to a quad in a named graphtype Quad struct {
S Term
P IRI
O Term
G Term
}
Quad represents an RDF quad (triple with optional graph name).
Methods:
IsZero() bool - Reports whether the quad has no subject/predicate/objectToTriple() Triple - Extracts the triple from a quad (ignores graph)InDefaultGraph() bool - Reports whether the quad is in the default graphToStatement() Statement - Converts quad to a statementtype Statement struct {
S Term
P IRI
O Term
G Term // nil for triples, non-nil for quads (can be omitted, defaults to nil)
}
Statement represents an RDF statement, which can be either a triple or a quad.
If G is nil (or omitted), it represents a triple. If G is non-nil, it represents a quad.
Creating Statements:
// Option 1: Omit G (defaults to nil for triples)
stmt := rdf.Statement{
S: rdf.IRI{Value: "http://example.org/s"},
P: rdf.IRI{Value: "http://example.org/p"},
O: rdf.IRI{Value: "http://example.org/o"},
// G omitted - defaults to nil (triple)
}
// Option 2: Use convenience function
stmt := rdf.NewTriple(
rdf.IRI{Value: "http://example.org/s"},
rdf.IRI{Value: "http://example.org/p"},
rdf.IRI{Value: "http://example.org/o"},
)
// For quads, specify G
quad := rdf.Statement{
S: rdf.IRI{Value: "http://example.org/s"},
P: rdf.IRI{Value: "http://example.org/p"},
O: rdf.IRI{Value: "http://example.org/o"},
G: rdf.IRI{Value: "http://example.org/g"},
}
// Or use convenience function
quad := rdf.NewQuad(
rdf.IRI{Value: "http://example.org/s"},
rdf.IRI{Value: "http://example.org/p"},
rdf.IRI{Value: "http://example.org/o"},
rdf.IRI{Value: "http://example.org/g"},
)
Methods:
IsTriple() bool - Reports whether the statement is a triple (G is nil)IsQuad() bool - Reports whether the statement is a quad (G is non-nil)AsTriple() Triple - Returns the statement as a triple (ignores graph)AsQuad() Quad - Returns the statement as a quadtype Format string
const (
FormatAuto Format = ""
// Triple formats
FormatTurtle Format = "turtle"
FormatNTriples Format = "ntriples"
FormatRDFXML Format = "rdfxml"
FormatJSONLD Format = "jsonld"
// Quad formats
FormatTriG Format = "trig"
FormatNQuads Format = "nquads"
)
Format represents an RDF serialization format.
Methods:
ParseFormat(s string) (Format, bool) - Parses a format stringIsQuadFormat() bool - Reports whether the format supports quadsString() string - Returns the canonical format nametype Reader interface {
Next() (Statement, error)
Close() error
}
Reader streams RDF statements from an input. A statement can be either a triple (G is nil) or a quad (G is non-nil).
Methods:
Next() (Statement, error) - Returns the next statement, or io.EOF when doneClose() error - Closes the reader and releases resourcestype Writer interface {
Write(Statement) error
Flush() error
Close() error
}
Writer streams RDF statements to an output. For triple-only formats, the graph (G) field is ignored.
Methods:
Write(Statement) error - Writes a statement to the outputFlush() error - Flushes any buffered dataClose() error - Closes the writer and releases resourcestype Handler func(Statement) error
Handler processes statements in push mode. It’s a function type that can be passed to Parse.
func NewReader(r io.Reader, format Format, opts ...Option) (Reader, error)
NewReader creates a reader for the specified format. If format is FormatAuto (empty string), the format is automatically detected. Auto-detection reads from the reader, so the reader position will be advanced.
Parameters:
r - Input readerformat - Format to read (use FormatAuto for auto-detection)opts - Optional configuration optionsReturns:
Reader - The reader instanceerror - Error if format is unsupported or initialization failsExample:
reader, err := rdf.NewReader(reader, rdf.FormatTurtle)
func NewWriter(w io.Writer, format Format, opts ...Option) (Writer, error)
NewWriter creates a writer for the specified format.
Parameters:
w - Output writerformat - Format to writeopts - Optional configuration optionsReturns:
Writer - The writer instanceerror - Error if format is unsupported or initialization failsExample:
writer, err := rdf.NewWriter(writer, rdf.FormatNTriples)
func Parse(ctx context.Context, r io.Reader, format Format, handler Handler, opts ...Option) error
Parse parses RDF from the reader and streams statements to the handler. If format is FormatAuto (empty string), the format is automatically detected.
Parameters:
ctx - Context for cancellationr - Input readerformat - Format to parse (use FormatAuto for auto-detection)handler - Handler function to process statementsopts - Optional configuration optionsReturns:
error - Error if parsing failsExample:
err := rdf.Parse(context.Background(), reader, rdf.FormatTurtle, func(s rdf.Statement) error {
// process statement
return nil
})
func ParseFormat(s string) (Format, bool)
ParseFormat normalizes a format string and returns a Format. Supports common aliases (e.g., “ttl” -> FormatTurtle, “nt” -> FormatNTriples).
Parameters:
s - Format string (e.g., “ttl”, “turtle”, “nt”, “trig”, “nq”)Returns:
Format - The format constantbool - True if format was recognizedSupported aliases:
Example:
format, ok := rdf.ParseFormat("ttl")
Options configure reader/writer behavior using functional options.
type Option func(*Options)
Option is a function that modifies Options.
type Options struct {
Context context.Context
// Security limits for untrusted input
MaxLineBytes int
MaxStatementBytes int
MaxDepth int
MaxTriples int64
// Format-specific options
AllowQuotedTripleStatement bool
DebugStatements bool
}
Options configures parser/writer behavior.
OptContext(ctx context.Context) Option - Set context for cancellation and timeoutsOptMaxLineBytes(maxBytes int) Option - Set maximum line size limitOptMaxStatementBytes(maxBytes int) Option - Set maximum statement size limitOptMaxDepth(maxDepth int) Option - Set maximum nesting depth limitOptMaxTriples(maxTriples int64) Option - Set maximum number of triples/quads to processOptSafeLimits() Option - Apply safe limits suitable for untrusted inputExample:
reader, err := rdf.NewReader(reader, rdf.FormatTurtle,
rdf.OptSafeLimits(),
rdf.OptMaxDepth(50),
rdf.OptContext(ctx),
)
var ErrUnsupportedFormat = errors.New("unsupported format")
ErrUnsupportedFormat is returned when a format is not supported by NewReader or NewWriter.
type ParseError struct {
Format string
Line int
Column int
Offset int
Err error
Message string
}
ParseError represents a parsing error with position information.
Methods:
Error() string - Returns a formatted error messageUnwrap() error - Returns the underlying errorAlways close readers and writers: Use defer reader.Close() or defer writer.Close()
Handle EOF properly: Check for io.EOF when Next() returns an error
Use streaming for large files: Use NewReader or Parse for efficient processing of large inputs
Check format support: Use ParseFormat to validate format strings before creating readers/writers
Use Statement type: The unified Statement type works with all formats. Use stmt.IsTriple() or stmt.IsQuad() to check the statement type.
Use context for cancellation: Pass a context to Parse to enable cancellation
Flush writers: Call Flush() before Close() to ensure all data is written
Set security limits: For untrusted input, always use OptSafeLimits() or set explicit limits