Skip to content

Go library

go-opcua is a pure Go OPC UA client and server over UA-TCP, WebSockets and HTTPS, with the OPC UA Binary encoding and the UA JSON mappings of WebSockets and HTTPS, with PubSub publishers and subscribers in the same module. It has no cgo. Cryptography is the Go standard library, plus ChaCha20-Poly1305 from golang.org/x/crypto, Ed448 and X448 from cloudflare/circl, and the Brainpool curves from ProtonMail/go-crypto. This page describes v1.31.0.

Terminal window
go get github.com/otfabric/go-opcua

Go 1.26 or later is required; CI tests Go 1.26 and 1.27. The packages you will use most:

Package Purpose
opcua Client, Node, subscriptions, options, retry, metrics
ua Types and codec: NodeID, Variant, DataValue, StatusCode, service messages
server Server, namespaces, access control, events, history providers
monitor Callback and channel based subscriptions (NodeMonitor)
errors Sentinel errors for errors.Is
id Well-known NodeID constants
gds Certificate management clients: push (gds.New) and pull from a Global Discovery Server (gds.NewPullClient)
gds/gdsserver A Global Discovery Server: application directory and certificate authority
pubsub PubSub runtime, with pubsub/transport/{udp,eth,mqtt,amqp}, pubsub/sks and pubsub/remote; see PubSub
uacp, uasc, uapolicy Transport, secure channel, security policies, certificates and PFX files (advanced use)

opcua.NewClient(endpoint, opts...) builds a client; Connect opens the SecureChannel and creates and activates a session. Dial opens only the SecureChannel (enough for discovery services). Close tears everything down; do not reuse a client after Close.

c, err := opcua.NewClient("opc.tcp://localhost:4840",
opcua.SecurityPolicy("None"),
opcua.SecurityMode(ua.MessageSecurityModeNone),
opcua.InsecureNoSecurity(), // required for policy None over opc.tcp
opcua.AuthAnonymous(),
)
if err != nil {
log.Fatal(err)
}
if err := c.Connect(ctx); err != nil {
log.Fatal(err)
}
defer c.Close(ctx)

Policies can be named by short name or full URI (http://opcfoundation.org/UA/SecurityPolicy#Basic256Sha256). opcua.SelectEndpoint skips policies the library does not implement and secured endpoints whose policy does not fit the certificate’s key type; with an empty certificate only unsecured endpoints remain. SelectEndpoint prefers opc.tcp endpoints; SelectEndpointForTransport picks among the endpoints of one transport profile. The TLS certificate of an opc.wss or opc.https server is checked against TLSConfig and the host name, separately from its application certificate. Over HTTPS there is no SecureChannel: the policy only signs the session, and a Publish is a long poll. The UA JSON mappings share the opc.wss and opc.https URLs with UA Binary, so the client uses them only when opcua.TransportProfile says so, which SecurityFromEndpoint sets from a JSON endpoint. wss-uajson is always security mode None, because a WebSocket cannot name a policy. UA-.NETStandard 2.0.1 takes JSON over HTTPS only as application/opcua+uajson: add opcua.HTTPSJSONContentType(uasc.HTTPSJSONContentTypeLegacy) for it. With reverse connect, create the client with "" to accept whatever endpoint URL the server announces. GetEndpoints, FindServers and FindServersOnNetwork accept the same ReverseConnect option.

main.go
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/otfabric/go-opcua"
"github.com/otfabric/go-opcua/ua"
)
func main() {
ctx := context.Background()
c, err := opcua.NewClient("opc.tcp://localhost:4840",
opcua.InsecureNoSecurity(), // a local test server without message security
opcua.AutoReconnect(true),
opcua.ReconnectInterval(5*time.Second),
opcua.WithConnStateHandler(func(s opcua.ConnState) {
log.Printf("State: %s", s)
}),
)
if err != nil {
log.Fatal(err)
}
if err := c.Connect(ctx); err != nil {
log.Fatal(err)
}
defer c.Close(ctx)
// Read the server time (i=2258).
dv, err := c.ReadValue(ctx, ua.NewNumericNodeID(0, 2258))
if err != nil {
log.Fatal(err)
}
fmt.Println("Server time:", dv.Value.Value())
// Subscribe to value changes.
sub, notifyCh, err := c.NewSubscription().
Interval(500 * time.Millisecond).
Monitor(ua.NewNumericNodeID(2, 1001)).
Start(ctx)
if err != nil {
log.Fatal(err)
}
defer sub.Cancel(ctx)
for msg := range notifyCh {
if msg.Error != nil {
log.Println("error:", msg.Error)
continue
}
if dcn, ok := msg.Value.(*ua.DataChangeNotification); ok {
for _, item := range dcn.MonitoredItems {
fmt.Printf("Value changed: %v\n", item.Value.Value.Value())
}
}
}
}

Read. ReadValue and ReadValues read the Value attribute. ReadMulti reads many node/attribute pairs and chunks the requests (32 items per request by default, ReadMultiWithChunkSize to change it). c.Node(id) gives helpers such as Value, DisplayName, BrowseName, NodeClass, AccessLevel and Summary (all common attributes in one call). ua.StandardNodeID("CurrentTime") returns a NodeID for a well-known name.

items := []opcua.ReadItem{
{NodeID: n1, AttributeID: ua.AttributeIDValue},
{NodeID: n2, AttributeID: ua.AttributeIDDisplayName},
}
results, err := c.ReadMulti(ctx, items)

Write. Every write returns a per-item StatusCode next to the Go error.

status, err := c.WriteValue(ctx,
ua.NewNumericNodeID(2, 1001),
&ua.DataValue{
EncodingMask: ua.DataValueValue,
Value: ua.MustVariant(42.0),
},
)
if err != nil {
log.Fatal(err)
}
if status != ua.StatusOK {
log.Fatal("write failed:", status)
}

WriteNodeValue(ctx, nodeID, value) wraps a plain Go value for you.

Browse and resolve paths. BrowseAll returns all references of a node; Node.BrowseAll is an iterator that follows continuation points; Node.BrowseWithDepth recurses on the client side.

node, err := c.NodeFromPath(ctx, "Server.ServerStatus") // from Objects, namespace 0
node, err = c.NodeFromQualifiedPath(ctx, "0:Server.0:ServerStatus")
node, err = c.NodeFromPathInNamespace(ctx, 1, "MyFolder.Sensor1.Temperature")

Subscriptions. The builder sets Interval (publishing), SamplingInterval, DataChangeFilter, MonitorItems (for QueueSize and DiscardOldest), MonitorEvents with an EventFilter, and Timestamps.

sub, notifs, err := c.NewSubscription().
Interval(250 * time.Millisecond).
DataChangeFilter(ua.DataChangeTriggerStatusValue, ua.DeadbandTypeAbsolute, 0.5).
Monitor(nodeID).
Start(ctx)

A server that cannot apply a filter rejects that item with a Bad status such as BadFilterNotAllowed or BadMonitoredItemFilterUnsupported; the other items are created. If the server closes the connection while creating a subscription or monitored items, the error wraps io.EOF. The monitor package (monitor.NewNodeMonitor(c)) offers channel and callback subscriptions by NodeID string.

Methods and history.

result, err := c.CallMethod(ctx, objectID, methodID, 42.0, "hello") // args wrapped in Variants
inputs, outputs, err := c.MethodArguments(ctx, objectID, methodID)
for dv, err := range c.ReadHistoryAll(ctx, nodeID, start, end) { // pages raw history
if err != nil {
log.Fatal(err)
}
fmt.Println(dv.SourceTimestamp, dv.Value.Value())
}

ReadHistory and ReadHistoryAll follow continuation points and release the one of a read that stops early. Historical events work the same way, with an EventFilter that selects the fields:

filter := ua.NewEventFilter().
Select("EventId", "Time", "Message", "Severity").
SelectPaths("2:Temperature"). // "ns:Name" segments name other namespaces
Build()
// Up to 50 events, newest first: a start after the end reads backward
events, err := c.ReadEventHistory(ctx, notifier, end, start, filter, 50)
// Every event of the range, 100 per HistoryRead
for ev, err := range c.ReadEventHistoryAll(ctx, notifier, start, end, filter, 100) {
if err != nil {
log.Fatal(err)
}
fmt.Println(ev.EventFields[1].Value(), ev.EventFields[2].Value())
}

HistoryUpdateEvents and HistoryDeleteEvents change event history, and HistoryReleaseContinuationPoints releases the points of a low-level HistoryReadEvent you do not finish. For services without a helper, use Client.Send. The modified, processed and at-time reads and HistoryUpdate of values (insert, replace, delete) have their own helpers. The browse helpers return a Bad browse status, such as BadNodeIdUnknown for a node that does not exist, as their error.

Alarms and conditions. Subscribe to events on the Server object with opcua.NewConditionEventFilter(), call ConditionRefresh to get the retained conditions, and answer each event with its EventId:

sub, ch, err := c.NewSubscription().
Interval(200*time.Millisecond).
MonitorEvents(opcua.NewConditionEventFilter(), ua.NewNumericNodeID(0, id.Server)).
Start(ctx)
if err != nil {
log.Fatal(err)
}
if err := sub.ConditionRefresh(ctx); err != nil {
log.Fatal(err)
}
for msg := range ch {
enl, ok := msg.Value.(*ua.EventNotificationList)
if !ok {
continue
}
for _, f := range enl.Events {
ev, err := opcua.ParseConditionEvent(f)
if err != nil || ev.ConditionID == nil { // RefreshStart and RefreshEnd have none
continue
}
if ev.Acked != nil && !*ev.Acked {
_ = c.Acknowledge(ctx, ev.ConditionID, ev.EventID, "seen")
}
}
}

Confirm, AddComment, EnableCondition and DisableCondition, timed and one-shot shelving, and the OPC UA 1.05 methods (Suppress, RemoveFromService, Silence, Reset, Respond for dialogs, and their *2 variants with a comment) are client methods too. ParseConditionEvent also reports branches and the 1.05 states, ReadAlarmMetrics reads alarm metrics, and NewAuditConditionEventFilter streams the audit events of who called which method; opcua.WithAuditEntryID(ctx, id) tags your own calls.

Server diagnostics. ServerDiagnosticsSummary, SessionDiagnostics, SubscriptionDiagnostics and SamplingIntervalDiagnostics read what the server counts. opcua.ReturnDiagnostics(ua.ReturnDiagnosticsAll) asks for DiagnosticInfos; a failed request then returns an *opcua.ServiceError with the resolved diagnostic, which still matches its status with errors.Is.

Package gds manages certificates by both models of Part 12. The push client needs a session with the SecurityAdmin role over SignAndEncrypt; it works against go-opcua, open62541, UA-.NETStandard and node-opcua servers:

g := gds.New(c)
tl, _ := g.ReadTrustList(ctx, ua.TrustListMasksAll)
tl.TrustedCertificates = append(tl.TrustedCertificates, newClientCA)
required, _ := g.WriteTrustList(ctx, tl)
csr, _ := g.CreateSigningRequest(ctx, &gds.SigningRequest{
CertificateType: gds.RsaSha256ApplicationCertificateType,
})
issued := myCA.Sign(csr) // your CA
required, _ = g.UpdateCertificate(ctx, &gds.CertificateUpdate{
CertificateType: gds.RsaSha256ApplicationCertificateType,
Certificate: issued,
IssuerCertificates: [][]byte{myCA.Cert},
})
if required {
_ = g.ApplyChanges(ctx)
}

WithTrustList selects the trust list of another certificate group (HTTPS, user tokens or a group of the application); GetCertificates, CreateSelfSignedCertificate, DeleteCertificate, ResetToServerDefaults and TransactionDiagnostics cover the rest of Part 12 1.05.

The pull client talks to a Global Discovery Server. Enroll registers or finds the application, requests a certificate, waits until it is issued and reads the trust list; the result plugs straight into a client or a server:

pc := gds.NewPullClient(c) // a session with the GDS over SignAndEncrypt
e, err := pc.Enroll(ctx, &gds.EnrollRequest{
Record: &gds.ApplicationRecord{ApplicationURI: uri, ApplicationType: ua.ApplicationTypeClient, ApplicationNames: names, ProductURI: product},
CertificateType: gds.EccNistP256ApplicationCertificateType,
Key: key, // nil: the GDS generates the key pair
})
opts, err := e.ClientOptions() // certificate, key and trusted CAs for opcua.NewClient

Requests work for every key type (RSA, NIST and Brainpool ECDSA, Ed25519, Ed448), and keys the GDS generates come as PEM or PFX. The pull model is verified against the Global Discovery Server of UA-.NETStandard.

  1. Create an application certificate. The URI subject alternative name is the ApplicationUri and is required. For testing, from the go-opcua security guide:

    Terminal window
    # RSA (Basic256Sha256 and the other RSA policies)
    openssl req -x509 -newkey rsa:2048 \
    -keyout key.pem -out cert.pem \
    -days 365 -nodes \
    -subj "/CN=OPC-UA Test" \
    -addext "subjectAltName=URI:urn:otfabric:opcua:client,DNS:localhost"
    # ECDSA P-256 (ECC_nistP256, ECC_nistP256_AesGcm, ECC_nistP256_ChaChaPoly)
    openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 \
    -keyout key.pem -out cert.pem \
    -days 365 -nodes \
    -subj "/CN=OPC-UA Test" \
    -addext "keyUsage=digitalSignature,nonRepudiation" \
    -addext "subjectAltName=URI:urn:otfabric:opcua:client,DNS:localhost"

    Use -newkey ed25519 for ECC_curve25519, -newkey ed448 for ECC_curve448, and ec_paramgen_curve:brainpoolP384r1 for both Brainpool policies. RSA keys need 2048 bits or more for every RSA policy; 4096 bits also works. Key files may be PKCS #1, PKCS #8 or SEC 1, PEM or DER. In production use certificates from your own CA and keep private keys at mode 0600.

  2. Trust the server. Pass the server’s CA (or self-signed certificate) with TrustedCertificates. It is the only trust list: the system CA pool is not used (Part 4 §6.1.3). The client checks the chain, validity period, key usage and, with SecurityFromEndpoint, the ApplicationUri. InsecureSkipVerify() disables all of this and is for development only.

  3. Get your certificate trusted by the server. Most servers reject unknown client certificates until an administrator trusts them.

  4. Pick the user token. AuthAnonymous() (default), AuthUsername, AuthCertificate with AuthPrivateKey or AuthPrivateKeySigner, or AuthIssuedToken. Always pair a password with SignAndEncrypt. AuthPolicyID overrides the UserTokenPolicy ID.

Mismatches are caught early: an RSA certificate on an ECC policy (or the reverse) fails with ErrInvalidSecurityConfig before anything is sent, and an unknown policy such as ECC_nistP521 fails with ErrUnsupportedSecurityPolicy. Brainpool and Ed448 certificates, which crypto/x509 cannot parse, are read by uapolicy; the Brainpool implementation is not constant time, so prefer the NIST or AEAD policies where the peer offers them. Keys in a hardware security module work for ECC through any crypto.Signer (PrivateKeySigner); RSA keys must be *rsa.PrivateKey.

main.go
package main
import (
"context"
"log"
"github.com/otfabric/go-opcua/id"
"github.com/otfabric/go-opcua/server"
"github.com/otfabric/go-opcua/ua"
)
func main() {
srv, err := server.New(
server.EndPoint("localhost", 4840),
server.EnableSecurity("None", ua.MessageSecurityModeNone),
server.InsecureNoSecurity(), // Start refuses policy None without it
server.EnableAuthMode(ua.UserTokenTypeAnonymous),
)
if err != nil {
log.Fatal(err)
}
ns := server.NewNodeNameSpace(srv, "http://example.com/myapp")
temperature := 21.5
node := server.NewVariableNode(
ua.NewNumericNodeID(ns.ID(), 1001),
"Temperature",
func() *ua.DataValue { return server.DataValueFromValue(temperature) },
)
ns.AddNode(node)
ns.Objects().AddRef(node, id.HasComponent, true)
if err := srv.Start(context.Background()); err != nil {
log.Fatal(err)
}
defer srv.Close()
select {} // run until killed
}

After changing a value, call srv.ChangeNotification(nodeID) so subscribers are sampled. server.NewMapNamespace is a simpler key/value namespace that notifies on SetValue. RegisterMethod adds method handlers, ImportNodeSetXML loads NodeSet2 models, EmitBaseEvent emits events, and SetHistorian(server.NewHistorian()) enables HistoryRead (raw, modified, at-time and processed) and HistoryUpdate. Node.SetMethodArguments gives a method its InputArguments and OutputArguments, which the Call service then checks.

More of the server.

  • Transports: server.WebSocketEndPoint(host, port) and server.HTTPSEndPoint(host, port) add opc.wss and opc.https listeners next to opc.tcp; server.TLSConfig sets their TLS certificate. server.EnableUAJSON() serves wss-uajson and https-uajson on the same listeners, advertised as twins of the binary endpoints.
  • Event history: srv.EnableEventHistory(notifier, server.EventHistoryOptions{Writable: true}) makes an Object a HistoricalEventNode. Every event reported on it, conditions and audit events included, goes to the historian (Historian.EnableEvents(notifier, maxEvents), 1000 per notifier by default), which serves HistoryRead of events with filters, paging and continuation points, and inserts, replaces, updates and deletes events. An EventHistoryProvider of your own can replace it.
  • Alarms: srv.AddCondition(server.ConditionConfig{...}) creates conditions and limit alarms with acknowledge, confirm, shelving, the 1.05 states, dialogs, branches, alarm groups and metrics. The application drives the state (SetActive, EvaluateLimits); clients call the methods through the Call service and the access controller.
  • Discovery: WithLocalDiscoveryServer makes the server an LDS, WithMulticastDiscovery announces it with mDNS, and WithReverseConnect dials listening clients.
  • Certificates: WithPushManagement serves the ServerConfiguration push model, and gds/gdsserver is a complete Global Discovery Server with a memory or file store.
  • PubSub: server.WithPubSub(cfg) publishes variables and events of the address space and writes received fields to variables; clients can reconfigure it through Server/PublishSubscribe. See PubSub.

For a secured server, add server.Certificate and server.PrivateKey (RSA), server.ApplicationIdentity(cert, key) once per ECC key type, and EnableSecurity per policy and mode. WithClientCertificateTrustList(caDER...) rejects untrusted client certificates at OpenSecureChannel with BadCertificateUntrusted. WithUsernameValidator and WithX509UserValidator check user tokens during ActivateSession, and WithAccessController decides each read, write, browse and call, and can be implemented outside the package (it receives a read-only *server.Session with the identity and roles). The DefaultAccessController allows everything; RBACAccessController checks roles. AllowUsernameOnNone() exists for test deployments only. ActivateSession accepts only the user token types an endpoint of the client’s channel offers (else Bad_IdentityTokenRejected), and a rejected ActivateSession leaves the session’s identity as it was.

Limits and write access (v1.31.0). WithMaxSessions (default 100), WithMaxSubscriptions (default 1024 for all sessions) and WithMaxSubscriptionsPerSession (default 64) bound what clients can create, with the defaults of open62541; past them CreateSession and CreateSubscription answer Bad_TooManySessions and Bad_TooManySubscriptions. The Write service enforces a node’s WriteMask for every attribute other than Value: nodes built with the Go API have none, so clients can write only their Value until you set ua.AttributeIDWriteMask on the node. NodeSet2 imports keep their WriteMask. Both sides keep to the message size and chunk count the peer announced.

Observing clients (v1.30.0). server.WithSessionObserver reports connections, activated and closed sessions, and refused requests (an untrusted certificate, a wrong password, a token type no endpoint offers) with the client’s address, security and identity; embed server.BaseSessionObserver for no-op defaults. With WithAuditing(true) the server raises the Part 4 security audit events for secure channels, sessions and refused certificates; the identity token in them carries no password. Session.Identity() no longer holds the password of a user name token.

There are two error surfaces. A Go error means the call did not complete normally (connection, session, configuration, transport); match it with errors.Is against sentinels in the errors package such as ErrNotConnected, ErrSessionClosed, ErrInvalidEndpoint, ErrNoMatchingEndpoint or ErrReverseHelloRejected. A ua.StatusCode is the server’s verdict on one item, and the Go error can be nil while items are Bad.

dv, err := c.ReadValue(ctx, nodeID)
if err != nil {
return err // client or transport failure
}
if dv.Status != ua.StatusOK {
return dv.Status // ua.StatusCode implements error
}

Do not treat a Bad item status as a reason to reconnect.

  • Every call takes a context.Context for cancellation and deadlines. DialTimeout bounds the TCP and HEL/ACK handshake (default 10 s) and, with reverse connect, the wait for the server. RequestTimeout sets a per-request timeout.
  • WithRetryPolicy attaches a RetryPolicy: NoRetry(), ExponentialBackoff(base, maxDelay, maxAttempts) or NewExponentialBackoff(cfg), where RetryOnTimeout defaults to false.
  • AutoReconnect is on by default. After a connection loss the client reopens the channel, restores or recreates the session and, per subscription, tries TransferSubscriptions, then Republish, then recreation. WithSubscriptionRecoveryHandler reports transferred, republished, recreated, partially_recovered or unrecoverable_gap.
  • One connected *Client is safe for concurrent ordinary service calls. Notification, connection-state and recovery callbacks run on library goroutines and must not block.

The library is silent by default. opcua.WithLogger(*slog.Logger) and server.SetLogger(...) turn logging on; nil restores silence. opcua.WithMetrics takes a ClientMetrics with OnRequest, OnResponse, OnError and OnTimeout callbacks per service name; the server has ServerMetrics via server.WithMetrics. Callbacks run on the request path and must not block.

  • The built-in historian accepts returnBounds without computing bounding values. Event history answers ReadEventDetails2 with ReadModified and ReadEventDetailsSorted with BadHistoryOperationUnsupported.
  • wss-uajson has security mode None only, because a WebSocket cannot name a security policy; TLS protects it.
  • Custom structures are decoded through registered Go types, not dynamically from the server’s DataTypeDefinition.
  • PubSub has no time-scheduled (TSN) Ethernet and no AMQP over WebSockets.
  • The push model has no file-based certificate store in the library: implement server.CertificateStore to persist pushed certificates.
  • Brainpool policies are not constant time; ECC Sign mode follows open62541 v1.5.9 where it differs from OPC UA 1.05.07.
  • Not certified by the OPC Foundation.

The go-opcua repository keeps a list of these gaps, and of the peer deviations you may meet, in Interop gaps and workarounds.