gomib

package module
v0.13.3-0...-7184e8a Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 23 Imported by: 0

README

gomib

CI PkgGoDev

Go library for parsing and querying SNMP MIB files.

Supports SMIv1 and SMIv2 modules. Loads MIBs from directories, directory trees, or embedded filesystems. Resolves imports, builds the OID tree, and provides typed access to objects, types, notifications, and conformance definitions.

Install

go get github.com/gosnmp/gomib

Requires Go 1.24+.

gomib has moved from github.com/golangsnmp/gomib to github.com/gosnmp/gomib. Update your Go module dependency and imports to github.com/gosnmp/gomib.

Quick start

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/gosnmp/gomib"
)

func main() {
    m, err := gomib.Load(context.Background(),
        gomib.WithSystemPaths(),
        gomib.WithModules("IF-MIB"),
    )
    if err != nil {
        log.Fatal(err)
    }

    obj := m.Object("ifIndex")
    if obj != nil {
        fmt.Printf("%s  %s  %s  %s\n", obj.Name(), obj.OID(), obj.Type().Name(), obj.Access())
        // ifIndex  1.3.6.1.2.1.2.2.1.1  InterfaceIndex  read-only
    }
}

Loading MIBs

// Load everything from a source (parses all files)
m, err := gomib.Load(ctx, gomib.WithSource(src))

// Load only specific modules and their transitive dependencies.
// Faster when the source contains hundreds of MIBs but you only need a few.
m, err := gomib.Load(ctx, gomib.WithSource(src), gomib.WithModules("IF-MIB", "IP-MIB"))
Sources

Dir recursively indexes a directory tree using content-derived module names. File/Files load individual files by path. FS wraps an fs.FS (useful with embed.FS). Multi tries multiple sources in order.

// Directory tree (indexed once at construction)
src, err := gomib.Dir("/usr/share/snmp/mibs")

// Individual files (module names auto-detected from content)
src, err := gomib.File("/path/to/IF-MIB.mib")
src, err  = gomib.Files("/path/to/IF-MIB.mib", "/path/to/IP-MIB.mib")

// Embedded filesystem
//go:embed mibs
var mibFS embed.FS
src := gomib.FS("embedded", mibFS)

// Combine sources (first match wins)
src := gomib.Multi(systemSrc, vendorSrc)

MustDir panics on error for use in var blocks.

Files are matched by extension: no extension, .mib, .smi, .txt, .my. Override with WithExtensions. Non-MIB files are filtered during loading by checking for DEFINITIONS and ::= in the content.

ScanModuleNames extracts module names from raw bytes without a full parse, useful for indexing:

names := gomib.ScanModuleNames(content) // e.g. ["IF-MIB"]

Sources can also list the modules they know about without parsing them:

src, _ := gomib.Dir("/usr/share/snmp/mibs")
names, _ := src.ListModules() // e.g. ["IF-MIB", "IP-MIB", ...]
Options
gomib.Load(ctx,
    gomib.WithSource(src),
    gomib.WithSystemPaths(),                             // discover net-snmp/libsmi paths
    gomib.WithLogger(slog.Default()),                    // enable debug/trace logging
    gomib.WithResolverStrictness(mib.ResolverPermissive),    // strictness preset
    gomib.WithDiagnosticConfig(mib.DiagnosticConfig{   // fine-grained control
        Reporting: mib.ReportingDefault,
        FailAt: mib.SeverityError,
        Ignore: []string{"identifier-underscore"},
    }),
)

Querying

Lookup methods take a plain name and return nil if not found:

obj := m.Object("ifIndex")
node := m.Node("ifEntry")
typ := m.Type("DisplayString")

For qualified lookup, scope through the module (see Module-scoped queries below).

Other lookup methods: Node, Type, Notification, Group, Compliance, Capability.

Symbol provides a unified lookup across all definition types:

sym := m.Symbol("ifIndex")       // returns a Symbol wrapping any definition kind
sym.Name()                       // "ifIndex"
sym.Object()                     // *Object (or nil if not an OBJECT-TYPE)
sym.Node()                       // *Node
sym.IsZero()                     // true if nothing was found
Resolve

Resolve accepts any common format - plain name, qualified name, or numeric OID - and returns the matching node:

node := m.Resolve("ifDescr")                     // plain name
node  = m.Resolve("IF-MIB::ifDescr")             // qualified
node  = m.Resolve("1.3.6.1.2.1.2.2.1.2")        // numeric OID
node  = m.Resolve(".1.3.6.1.2.1.2.2.1.2")       // leading dot

ResolveOID converts any of those formats to a numeric OID, and also handles instance-suffixed forms:

oid, err := m.ResolveOID("IF-MIB::ifDescr.5")    // OID{1,3,6,1,2,1,2,2,1,2,5}
oid, err  = m.ResolveOID("ifDescr.5")             // same result
oid, err  = m.ResolveOID("1.3.6.1.2.1.2.2.1.2")  // numeric pass-through

ResolveOID is the inverse of FormatOID:

formatted := m.FormatOID(oid)       // "IF-MIB::ifDescr.5"
back, _   := m.ResolveOID(formatted) // round-trips to the same OID
OID lookups

For cases where you already know the format, lower-level methods avoid parsing:

oid, _ := mib.ParseOID("1.3.6.1.2.1.2.2.1.1")
node := m.NodeByOID(oid)            // exact match
node  = m.LongestPrefixByOID(oid)   // longest matching prefix

LookupInstance returns both the matched node and the instance suffix, which is the standard pattern for processing SNMP varbinds:

lookup := m.LookupInstance(oid)
lookup.Node().Name()   // "ifIndex"
lookup.Suffix()        // OID{5} (trailing arcs after the matched node)
Module-scoped queries
mod := m.Module("IF-MIB")
obj := mod.Object("ifIndex")
typ := mod.Type("InterfaceIndex")
Module metadata and imports

Module exposes both MODULE-IDENTITY metadata and import-resolution details:

mod := m.Module("IF-MIB")

mod.Name()         // "IF-MIB"
mod.Language()     // SMIv2
mod.SourcePath()   // file path, or "" for embedded base modules
mod.IsBase()       // false for user/system modules, true for built-ins
mod.OID()          // module identity OID
mod.Organization() // ORGANIZATION clause
mod.ContactInfo()  // CONTACT-INFO clause
mod.Description()  // DESCRIPTION clause
mod.LastUpdated()  // LAST-UPDATED value
mod.Revisions()    // []Revision
mod.Imports()      // []Import from the IMPORTS clause

mod.ImportsSymbol("DisplayString") // true if listed in IMPORTS
mod.IsImportUsed("DisplayString")  // true if referenced during resolution
mod.ImportSource("DisplayString")  // resolved source module

Base modules are always present and define the SMI language itself:

base := m.Module("SNMPv2-SMI")
base.IsBase()      // true
base.SourcePath()  // ""
base.Node("enterprises").OID() // 1.3.6.1.4.1

Module introspection methods:

mod.DefinesSymbol("ifIndex")        // true if module defines this name
mod.ImportsSymbol("DisplayString")  // true if module imports this name
mod.IsImportUsed("DisplayString")   // true if import was referenced during resolution
mod.ImportSource("DisplayString")   // *Module for the source of the import

for sym := range mod.Definitions() {  // iterate all definitions as Symbol values
    fmt.Println(sym.Name())
}
Collections
m.Objects()        // all OBJECT-TYPE definitions
m.Tables()         // tables only
m.Scalars()        // scalars only
m.Columns()        // columns only
m.Rows()           // rows only
m.Types()          // all type definitions
m.Notifications()  // all notifications
m.Groups()         // all groups
m.Compliances()    // all compliances
m.Capabilities()   // all capabilities
m.Modules()        // all loaded modules
m.AllSymbols()     // all definitions across all modules (iter.Seq[Symbol])
OID tree iteration
for node := range m.Nodes() {
    fmt.Println(node.OID(), node.Name(), node.Kind())
}

// Subtree iteration
node := m.Node("ifEntry")
for child := range node.Subtree() {
    fmt.Println(child.Name())
}

// Node metadata (populated for base module OIDs and OBJECT-IDENTITY definitions)
node.Description() // OID assignment description text
node.Reference()   // reference string

Objects

Each Object carries its type, access level, status, and position in the OID tree:

obj := m.Object("ifType")

obj.Name()        // "ifType"
obj.OID()         // 1.3.6.1.2.1.2.2.1.3
obj.Kind()        // column
obj.Access()      // read-only
obj.Status()      // current
obj.Type().Name() // "IANAifType"
obj.Units()       // "" (empty if not set)
obj.Description() // "The type of interface..."
Tables
table := m.Object("ifTable")
table.IsTable()  // true

row := table.Entry()           // ifEntry
cols := row.Columns()          // [ifIndex, ifDescr, ifType, ...]
idxs := row.EffectiveIndexes() // handles AUGMENTS

for _, idx := range idxs {
    fmt.Printf("INDEX %s (implied=%v)\n", idx.Object.Name(), idx.Implied)
}

Navigate from any level: obj.Table() returns the containing table, obj.Row() returns the containing row.

Effective constraints

Constraints can be defined inline on an object or inherited through its type chain. Effective SIZE and value ranges are intersections of every applicable constraint in the parent chain and the base type domain, so they can be narrower than any one declared list:

ranges := obj.EffectiveRanges() // intersected value ranges
sizes := obj.EffectiveSizes()   // intersected SIZE constraints

obj.EffectiveRangesConstrained() // any applicable value constraint exists
obj.EffectiveSizesConstrained()  // any applicable SIZE constraint exists
obj.EffectiveEnums()             // nearest enum values
obj.EffectiveBits()              // nearest BITS values
obj.EffectiveDisplayHint()       // nearest display hint string

An empty effective slice is ambiguous by itself. If the corresponding Effective*Constrained() method is false, the value is unconstrained; if it is true, the declared constraints have an empty intersection. The same methods are available on Type.

Each mib.Range is inclusive and has Min and Max endpoints of type mib.RangeBound. Endpoint kinds preserve signed values, unsigned values through math.MaxUint64, symbolic MIN/MAX, and unresolved source text:

for i := range ranges {
    r := &ranges[i]
    if !r.IsResolved() { // symbolic or raw endpoint remains
        fmt.Println(r.Min.Kind, r.Min.String(), r.Max.Kind, r.Max.String())
        continue
    }

    if min, ok := r.Min.AsInt64(); ok {
        fmt.Println("signed-compatible minimum:", min)
    }
    if max, ok := r.Max.AsUint64(); ok {
        fmt.Println("unsigned-compatible maximum:", max)
    }
}

AsInt64() accepts signed endpoints and unsigned endpoints no greater than math.MaxInt64. AsUint64() accepts unsigned endpoints and non-negative signed endpoints. Both return ok == false for unrepresentable numeric values, symbolic MIN/MAX, and raw endpoints. Inspect RangeBound.Kind (RangeBoundSigned, RangeBoundUnsigned, RangeBoundMin, RangeBoundMax, or RangeBoundRaw) when the distinction matters.

Types

Types form chains: a textual convention references a parent type, which may reference another, down to a base SMI type.

typ := m.Type("DisplayString")

typ.Name()                // "DisplayString"
typ.IsTextualConvention() // true
typ.Base()                // OCTET STRING
typ.DisplayHint()         // "255a"
typ.Sizes()               // [{0 255}]
typ.Parent().Name()       // base type reference

// Walk the chain
for t := typ; t != nil; t = t.Parent() {
    fmt.Printf("%s (base: %s)\n", t.Name(), t.Base())
}

// Effective values resolve through the chain
typ.EffectiveBase()              // underlying base type
typ.EffectiveDisplayHint()       // first non-empty hint in chain
typ.EffectiveEnums()             // first non-empty enum set
typ.EffectiveRanges()            // intersection across the chain
typ.EffectiveSizes()             // SIZE intersection across the chain
typ.EffectiveRangesConstrained() // distinguishes absent from empty
typ.EffectiveSizesConstrained()  // distinguishes absent from empty

Classification helpers: IsCounter(), IsGauge(), IsString(), IsEnumeration(), IsBits().

Notifications

notif := m.Notification("linkDown")

notif.Name()        // "linkDown"
notif.OID()         // 1.3.6.1.6.3.1.1.5.3
notif.Status()      // current
notif.Description() // "A linkDown trap..."

for _, obj := range notif.Objects() {
    fmt.Printf("  varbind: %s (%s)\n", obj.Name(), obj.OID())
}

SMIv1 TRAP-TYPE definitions populate TrapInfo():

if trap := notif.TrapInfo(); trap != nil {
    fmt.Printf("enterprise=%s trap-number=%d\n", trap.Enterprise, trap.TrapNumber)
}

Conformance

gomib also exposes OBJECT-GROUP, NOTIFICATION-GROUP, MODULE-COMPLIANCE, and AGENT-CAPABILITIES:

grp := m.Group("ifGeneralInformationGroup")
grp.IsNotificationGroup() // false for OBJECT-GROUP
for _, member := range grp.Members() {
    fmt.Println(member.Name(), member.OID())
}

comp := m.Compliance("ifCompliance3")
for _, mod := range comp.Modules() {
    fmt.Println("MODULE", mod.ModuleName) // empty = current module
    fmt.Println("mandatory groups:", mod.MandatoryGroups)
}

cap := m.Capability("someAgentCaps")
if cap != nil {
    fmt.Println(cap.ProductRelease())
    for _, sup := range cap.Supports() {
        fmt.Println("SUPPORTS", sup.ModuleName, sup.Includes)
    }
}

Diagnostics

Loading produces diagnostics for issues found during parsing and resolution.

m, err := gomib.Load(ctx, gomib.WithSource(src))

// Check for errors
if m.HasErrors() {
    fmt.Println("errors found")
}

// Inspect all diagnostics
for _, d := range m.Diagnostics() {
    fmt.Printf("[%s] %s: %s (line %d)\n", d.Severity, d.Module, d.Message, d.Line)
}

// Check unresolved references
for _, ref := range m.Unresolved() {
    fmt.Printf("unresolved %s: %s in %s\n", ref.Kind, ref.Symbol, ref.Module)
}
Strictness and Reporting

Resolver strictness controls fallback behavior:

Resolver strictness Constant Behavior
Strict ResolverStrict Tier 1 only (deterministic scope/import resolution)
Normal ResolverNormal Tier 1 + Tier 2 (constrained assumptions)
Permissive ResolverPermissive Tier 1 + Tier 2 + Tier 3 (global search fallbacks)
m, _ := gomib.Load(ctx, gomib.WithSource(src), gomib.WithResolverStrictness(mib.ResolverPermissive))

Diagnostic reporting is independent and configured with WithDiagnosticConfig:

gomib.WithDiagnosticConfig(mib.DiagnosticConfig{
    Reporting: mib.ReportingDefault,
    FailAt: mib.SeverityError,              // fail on Error or worse
    Ignore: []string{"identifier-underscore"}, // suppress specific codes
    Overrides: map[string]mib.Severity{
        "import-not-found": mib.SeverityWarning, // downgrade to warning
    },
})

The CLI combines resolver and failure settings into modes.

  • Normal and strict modes fail loading on severe or fatal diagnostics. --permissive enables all resolver fallbacks and sets the failure threshold to fatal.
  • --report silent|quiet|default|verbose controls diagnostic output for load and dump. All reporting levels use the same exit policy.
  • get, find, and inspect default to permissive mode. inspect collects verbose diagnostics for the selected symbol.
  • gomib lint is separate from resolver strictness and filters diagnostics by severity.

Syntax and Tokenization

The syntax package provides direct access to the lexer, parser, and concrete syntax tree (CST) for tooling, language servers, linters, or syntax highlighting.

Tokenization
import "github.com/gosnmp/gomib/syntax"

source := []byte(`ifIndex OBJECT-TYPE SYNTAX InterfaceIndex`)
tokens := syntax.Tokenize(source)

for _, tok := range tokens {
    if tok.Kind == syntax.TokEOF {
        break
    }
    text := source[tok.Span.Start:tok.Span.End]
    fmt.Printf("%-20s %s\n", tok.Kind.LibsmiName(), text)
}

Token kind classification methods on TokenKind:

tok.Kind.IsKeyword()             // any keyword
tok.Kind.IsMacroKeyword()        // OBJECT-TYPE, MODULE-IDENTITY, etc.
tok.Kind.IsTypeKeyword()         // INTEGER, Counter32, OCTET, etc.
tok.Kind.IsClauseKeyword()       // SYNTAX, MAX-ACCESS, STATUS, etc.
tok.Kind.IsIdentifier()          // uppercase or lowercase identifier
tok.Kind.IsStructuralKeyword()   // DEFINITIONS, BEGIN, END, IMPORTS, etc.
tok.Kind.IsStatusAccessKeyword() // current, deprecated, read-only, etc.
Parsing to CST

Parse produces a lossless concrete syntax tree that preserves every byte of the original source, including whitespace and comments. This is useful for tooling that needs structural information without running the full resolution pipeline.

file, diags := syntax.Parse(source)

for _, mod := range file.Modules {
    name := string(source[mod.Name.Span.Start:mod.Name.Span.End])
    fmt.Printf("module %s: %d definitions\n", name, len(mod.Body))

    for _, def := range mod.Body {
        switch d := def.(type) {
        case *syntax.ObjectTypeNode:
            fmt.Printf("  OBJECT-TYPE %s\n", source[d.Name.Span.Start:d.Name.Span.End])
        case *syntax.ModuleIdentityNode:
            fmt.Printf("  MODULE-IDENTITY %s\n", source[d.Name.Span.Start:d.Name.Span.End])
        }
    }
}

// Round-trip: reconstructing from the CST reproduces the original source exactly
reconstructed := syntax.ReconstructText(file, source)
Line tables

LineTable provides bidirectional conversion between byte offsets (used by spans) and line/column numbers (used by editors and LSP):

lt := syntax.BuildLineTable(source)
line, col := lt.LineCol(tok.Span.Start)       // byte offset -> line/col
offset, ok := lt.Offset(cursorLine, cursorCol) // line/col -> byte offset
Span queries on resolved modules

The resolved model provides span-based queries for language server features like go-to-definition and hover:

mod := m.Module("IF-MIB")
offset, ok := mod.Offset(cursorLine, cursorCol) // line/col -> byte offset
if ok {
    sc := mod.SpanContext(offset)
    switch sc.Kind {
    case mib.SpanContextImport:
        fmt.Printf("import %s from %s\n", sc.Name, sc.Module)
    case mib.SpanContextOidRef:
        fmt.Printf("OID reference to %s\n", sc.Name)
    case mib.SpanContextSyntax:
        fmt.Printf("SYNTAX type %s\n", sc.Name)
    case mib.SpanContextDefinition:
        fmt.Printf("definition %s in %s\n", sc.Name, sc.Module)
    }
}

CLI

The cmd/gomib tool provides a command-line interface for MIB operations:

gomib load IF-MIB                    # load and show statistics
gomib get -m IF-MIB ifIndex          # query by name
gomib get -m IF-MIB 1.3.6.1.2.1.2   # query by OID
gomib inspect ifDescr                # deep-dive with type chain, provenance, diagnostics
gomib dump IF-MIB                    # JSON output
gomib lint IF-MIB                    # check for issues
gomib find -p testdata/corpus/primary 'if*'        # search by pattern
gomib normalize IF-MIB               # emit canonical SMIv2 text
gomib trace -m IF-MIB ifEntry        # trace resolution
gomib paths                          # show search paths
gomib list                           # list available modules

Use -p PATH to specify MIB search paths (repeatable). Without -p, paths are discovered from net-snmp and libsmi configuration (config files, MIBDIRS/SMIPATH env vars, standard default directories).

See cmd/gomib/README.md for full command reference.

Documentation

Overview

Package gomib loads and resolves SNMP MIB modules.

Call Load with one or more Source values to parse MIB files, resolve cross-module imports, build the OID tree, and return a read-only mib.Mib containing the merged result.

Overview

Most callers should stay at this package layer:

  • Load runs the full parse, validate, and resolve pipeline.
  • Source implementations such as Dir, File, Files, FS, and Multi control where modules are found.
  • WithModules limits loading to selected modules and their transitive dependencies.
  • WithSystemPaths discovers net-snmp and libsmi search paths.

Query Model

The resolved query model lives in the github.com/gosnmp/gomib/mib package. Callers typically load through Load here, then query the resulting mib.Mib for modules, objects, types, notifications, table structure, and OID lookups.

Lower-Level Access

For lower-level lexical access without full loading, use the github.com/gosnmp/gomib/token package.

Index

Constants

View Source
const LevelTrace = types.LevelTrace

LevelTrace is a custom log level more verbose than Debug. Use for per-item iteration logging (tokens, OID nodes, imports). Enable with: &slog.HandlerOptions{Level: slog.Level(-8)}

Variables

View Source
var ErrDiagnosticThreshold = errors.New("diagnostic threshold exceeded")

ErrDiagnosticThreshold is returned when diagnostics exceed the configured FailAt severity. The Mib is still returned with all resolved data.

View Source
var ErrMissingModules = errors.New("requested modules not found")

ErrMissingModules is returned when WithModules names are not found in any source. The Mib is still returned with whatever modules could be loaded.

View Source
var ErrNoSources = errors.New("no MIB sources provided")

ErrNoSources is returned when Load is called with no sources.

Functions

func DefaultExtensions

func DefaultExtensions() []string

DefaultExtensions returns the file extensions recognized as MIB files. Empty string matches files with no extension (e.g., "IF-MIB").

func DiscoverSystemPaths

func DiscoverSystemPaths() []string

DiscoverSystemPaths returns MIB directories from net-snmp and libsmi configuration, deduplicated and filtered to directories that exist.

func Load

func Load(ctx context.Context, opts ...LoadOption) (*mib.Mib, error)

Load loads MIB modules from configured sources and resolves them.

Example:

m, err := gomib.Load(ctx,
    gomib.WithSource(gomib.MustDir("/usr/share/snmp/mibs")),
    gomib.WithModules("IF-MIB", "IP-MIB"),
)

m, err := gomib.Load(ctx, gomib.WithSystemPaths())

func ScanModuleNames

func ScanModuleNames(content []byte) []string

ScanModuleNames extracts module names from raw MIB file bytes by finding identifiers that precede "DEFINITIONS ::=". This is a lightweight scan, not a full parse. ASN.1 comments are skipped so that commented-out module headers are not indexed. Returns nil if no module headers are found.

Types

type FindResult

type FindResult struct {
	Content []byte
	// Path is used in diagnostic messages to identify the source.
	Path string
}

FindResult holds the content and location of a found MIB file.

type LoadOption

type LoadOption func(*loadConfig)

LoadOption configures Load.

func WithDiagnosticConfig

func WithDiagnosticConfig(cfg mib.DiagnosticConfig) LoadOption

WithDiagnosticConfig sets the diagnostic reporting and failure configuration.

DiagnosticConfig controls independent diagnostic policies:

  • Reporting: the baseline severity retained in mib.Mib.Diagnostics.
  • Overrides: the effective severity stored on matching diagnostics.
  • Ignore: which non-fatal diagnostics are suppressed entirely.
  • FailAt: which stored severity causes Load to return ErrDiagnosticThreshold.

This is separate from WithResolverStrictness, which controls how the resolver handles ambiguous or missing references. A permissive resolver still collects diagnostics, and those diagnostics are still subject to the FailAt threshold. Callers loading large vendor MIB sets typically want both permissive resolution and a relaxed FailAt (e.g. SeverityFatal).

func WithLogger

func WithLogger(logger *slog.Logger) LoadOption

WithLogger sets the logger for debug/trace output. If not set, no logging occurs (zero overhead).

func WithModules

func WithModules(names ...string) LoadOption

WithModules restricts loading to the named modules and their dependencies. Omit to load all modules from the configured sources.

func WithResolverStrictness

func WithResolverStrictness(level mib.ResolverStrictness) LoadOption

WithResolverStrictness sets resolver fallback behavior for ambiguous or missing references.

This controls which heuristic fallbacks the resolver may use:

This does not affect diagnostic failure policy. A permissive resolver still produces diagnostics that may exceed the mib.DiagnosticConfig.FailAt threshold. To also suppress failure on non-fatal diagnostics, configure WithDiagnosticConfig with FailAt set to mib.SeverityFatal.

func WithSource

func WithSource(src ...Source) LoadOption

WithSource appends one or more MIB sources to the load configuration. Sources are searched in the order they are added.

func WithSystemPaths

func WithSystemPaths() LoadOption

WithSystemPaths enables automatic discovery of MIB search paths from net-snmp and libsmi configuration (config files, env vars, defaults). Discovered paths are appended after any explicit source, serving as fallback. When source is nil and WithSystemPaths is set, system paths alone are sufficient.

type Source

type Source interface {
	// Find returns the MIB content for the named module,
	// or fs.ErrNotExist if the module is not available.
	Find(name string) (FindResult, error)

	// ListModules returns all module names known to this source.
	ListModules() ([]string, error)
}

Source provides access to MIB files for the loading pipeline. Implementations are passed to WithSource and searched in order during Load to locate module files by name. The standard implementations are Dir, FS, and Multi.

func Dir

func Dir(root string, opts ...SourceOption) (Source, error)

Dir creates a Source that recursively indexes a directory tree. It walks the tree once at construction and builds a name->path index using content-derived module names (not filenames). First match wins for duplicate names.

func DiscoverSystemSources

func DiscoverSystemSources() []Source

DiscoverSystemSources returns Sources for all discovered system MIB directories.

func FS

func FS(name string, fsys fs.FS, opts ...SourceOption) Source

FS creates a Source backed by an fs.FS (e.g., embed.FS). The name is used as a prefix in diagnostic paths. The filesystem is lazily indexed on first use. Errors are deferred to the first Find or ListModules call.

func File

func File(path string) (Source, error)

File creates a Source from a single MIB file on disk. The module name is extracted from the file content by scanning for "DEFINITIONS ::=" headers, just like Dir does for directory trees. The caller does not need to know or provide the module name.

func Files

func Files(paths ...string) (Source, error)

Files creates a Source from multiple MIB files on disk. Module names are extracted from each file's content by scanning for "DEFINITIONS ::=" headers. When duplicate module names appear across files, the first file wins.

func Multi

func Multi(sources ...Source) Source

Multi combines multiple sources into one. Find() tries each source in order, returning the first match.

func MustDir

func MustDir(root string, opts ...SourceOption) Source

MustDir is like Dir but panics on error.

type SourceOption

type SourceOption func(*sourceConfig)

SourceOption modifies source behavior.

func WithExtensions

func WithExtensions(exts ...string) SourceOption

WithExtensions overrides the default file extensions used to match MIB files. Extensions are normalized to lowercase with a leading dot (e.g. "mib" becomes ".mib"). An empty string matches files with no extension.

Directories

Path Synopsis
cmd
gomib command
Command gomib is a CLI tool for loading, querying, and dumping MIB modules.
Command gomib is a CLI tool for loading, querying, and dumping MIB modules.
gomib-fixturegen command
gomib-fixturegen generates NormalizedNode JSON fixtures from gomib for cross-validation with mib-rs.
gomib-fixturegen generates NormalizedNode JSON fixtures from gomib for cross-validation with mib-rs.
gomib-libsmi command
Command gomib-libsmi compares gomib against libsmi for lexer/parser cross-validation.
Command gomib-libsmi compares gomib against libsmi for lexer/parser cross-validation.
gomib-netsnmp command
Command gomib-netsnmp compares gomib against net-snmp for cross-validation.
Command gomib-netsnmp compares gomib against net-snmp for cross-validation.
internal/cliutil
Package cliutil provides shared CLI utilities for gomib command-line tools.
Package cliutil provides shared CLI utilities for gomib command-line tools.
examples
basic command
Load IF-MIB and print a module summary with selected objects.
Load IF-MIB and print a module summary with selected objects.
diagnostics command
Load MIBs at different strictness levels and show diagnostic output.
Load MIBs at different strictness levels and show diagnostic output.
embed command
Use embed.FS with gomib.FS() to load MIBs embedded in the binary.
Use embed.FS with gomib.FS() to load MIBs embedded in the binary.
modules command
Load embedded modules and inspect module metadata, imports, and visible symbols.
Load embedded modules and inspect module metadata, imports, and visible symbols.
notifications command
Load an embedded module and inspect notifications, groups, compliances, and capabilities.
Load an embedded module and inspect notifications, groups, compliances, and capabilities.
query command
Show different query patterns: by name, module-scoped, OID, and prefix matching.
Show different query patterns: by name, module-scoped, OID, and prefix matching.
tables command
Load several MIBs and demonstrate the table API: structure, indexes, columns, AUGMENTS relationships, index encoding, and navigation.
Load several MIBs and demonstrate the table API: structure, indexes, columns, AUGMENTS relationships, index encoding, and navigation.
tokens command
types command
Show type chain walking, textual conventions, and effective constraints.
Show type chain walking, textual conventions, and effective constraints.
internal
cst
cst/lower
Package lower transforms CST nodes into module IR types.
Package lower transforms CST nodes into module IR types.
cst/parser
Package parser provides a lossless CST parser for SMI MIB modules.
Package parser provides a lossless CST parser for SMI MIB modules.
graph
Package graph provides dependency graph construction and analysis for MIB resolution.
Package graph provides dependency graph construction and analysis for MIB resolution.
lexer
Package lexer provides tokenization for SMIv1/SMIv2 MIB source text.
Package lexer provides tokenization for SMIv1/SMIv2 MIB source text.
model
Package model defines the resolved MIB data model types.
Package model defines the resolved MIB data model types.
module
Package module provides a normalized representation of MIB modules.
Package module provides a normalized representation of MIB modules.
testutil
Package testutil provides test assertion helpers.
Package testutil provides test assertion helpers.
types
Package types provides internal types shared across gomib packages.
Package types provides internal types shared across gomib packages.
Package mib re-exports the resolved MIB data model and resolver entry point.
Package mib re-exports the resolved MIB data model and resolver entry point.
Package smiwrite emits resolved MIB models as canonical SMIv2 text.
Package smiwrite emits resolved MIB models as canonical SMIv2 text.
Package syntax provides public access to the SMI MIB concrete syntax tree (CST), token types, and token kind constants.
Package syntax provides public access to the SMI MIB concrete syntax tree (CST), token types, and token kind constants.

Jump to

Keyboard shortcuts

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