zerobus
A small D-Bus client for Go that does not allocate once it is running.
go get github.com/bnema/zerobus # Go 1.24 or newer
- Zero allocations per message. After the first few messages warm up its buffers, a call, a reply or a signal costs no heap allocation.
- Zero-copy reads. Strings and byte arrays point straight into the receive buffer.
- Standard library only.
- Small. It connects over a Unix socket, authenticates with
EXTERNAL, calls methods, emits signals, answers calls, and adds match rules. Nothing else.
Status: v0.x. The API may change between minor versions.
Call a method
c, err := zerobus.SessionBus()
if err != nil {
log.Fatal(err)
}
defer c.Close()
e := c.NewCall("org.freedesktop.DBus", "/org/freedesktop/DBus",
"org.freedesktop.DBus", "GetNameOwner", "s")
e.Str("org.freedesktop.Notifications")
m, err := c.Call()
if err != nil {
log.Fatal(err) // a D-Bus error reply is a *zerobus.Error
}
owner := m.Body().Str()
Build a message with NewCall, NewSignal, NewReply or NewError, write its body in the order of its signature, then send it with Call (wait for the reply) or Send (do not wait). Before sending, zerobus reads the whole body back with its signature and checks names, paths and strings, so an invalid message returns ErrInvalid instead of getting the connection dropped by the bus.
Read values
Read values in the order of the signature. Errors are sticky: check Err() once at the end.
r := m.Body() // signature "a{sv}"
end := r.Array('{')
for r.More(end) {
r.Struct()
key := r.Str()
switch sig := r.Variant(); sig {
case "s":
fmt.Println(key, r.Str())
default:
r.Skip(sig) // skip values you do not need
}
}
if err := r.Err(); err != nil {
return err
}
A received message is valid only until the next ReadMessage or Call. The strings and byte slices it returns point into the receive buffer and are overwritten by the next message. Copy what you keep:
name := strings.Clone(r.Str())
icon := bytes.Clone(r.ByteArray())
Receive signals
c.AddMatch("type='signal',interface='org.kde.StatusNotifierItem'")
for {
m, err := c.ReadMessage()
if err != nil {
return err
}
if m.Type == zerobus.TypeSignal {
fmt.Println(m.Sender, m.Member)
}
}
Call reads messages until its reply arrives. Set Conn.Handle to receive the messages that arrive meanwhile; they are dropped otherwise. Handle may send (answer a call, emit a signal), but not wait: Call and ReadMessage return ErrNested inside it.
Answer calls
c.RequestName("org.example.Echo", zerobus.NameFlagDoNotQueue)
for {
m, err := c.ReadMessage()
if err != nil {
return err
}
if m.Type == zerobus.TypeMethodCall && m.Member == "Echo" {
c.NewReply(m, "s").Str(m.Body().Str())
c.Send()
}
}
Concurrency
A Conn is not safe for concurrent use. Use it from one goroutine, usually an event loop around ReadMessage. Close may be called from any goroutine: a blocked ReadMessage then returns ErrClosed.
Not supported
- Transports other than
unix:path and unix:abstract (no TCP, no launchd, no autolaunch).
- Passing file descriptors (
UNIX_FD values can be read, but no descriptors are received).
- Authentication other than
EXTERNAL.
- Reflection-based marshalling, introspection and code generation.
Example
examples/trayitems lists the system tray items on the session bus and prints their changes.
License
MIT
source
1# zerobus
2
3A small D-Bus client for Go that does not allocate once it is running.
4
5```sh
6go get github.com/bnema/zerobus # Go 1.24 or newer
7```
8
9- **Zero allocations per message.** After the first few messages warm up its buffers, a call, a reply or a signal costs no heap allocation.
10- **Zero-copy reads.** Strings and byte arrays point straight into the receive buffer.
11- **Standard library only.**
12- **Small.** It connects over a Unix socket, authenticates with `EXTERNAL`, calls methods, emits signals, answers calls, and adds match rules. Nothing else.
13
14**Status: v0.x.** The API may change between minor versions.
15
16## Call a method
17
18```go
19c, err := zerobus.SessionBus()
20if err != nil {
21 log.Fatal(err)
22}
23defer c.Close()
24
25e := c.NewCall("org.freedesktop.DBus", "/org/freedesktop/DBus",
26 "org.freedesktop.DBus", "GetNameOwner", "s")
27e.Str("org.freedesktop.Notifications")
28
29m, err := c.Call()
30if err != nil {
31 log.Fatal(err) // a D-Bus error reply is a *zerobus.Error
32}
33owner := m.Body().Str()
34```
35
36Build a message with `NewCall`, `NewSignal`, `NewReply` or `NewError`, write its body in the order of its signature, then send it with `Call` (wait for the reply) or `Send` (do not wait). Before sending, zerobus reads the whole body back with its signature and checks names, paths and strings, so an invalid message returns `ErrInvalid` instead of getting the connection dropped by the bus.
37
38## Read values
39
40Read values in the order of the signature. Errors are sticky: check `Err()` once at the end.
41
42```go
43r := m.Body() // signature "a{sv}"
44end := r.Array('{')
45for r.More(end) {
46 r.Struct()
47 key := r.Str()
48 switch sig := r.Variant(); sig {
49 case "s":
50 fmt.Println(key, r.Str())
51 default:
52 r.Skip(sig) // skip values you do not need
53 }
54}
55if err := r.Err(); err != nil {
56 return err
57}
58```
59
60**A received message is valid only until the next `ReadMessage` or `Call`.** The strings and byte slices it returns point into the receive buffer and are overwritten by the next message. Copy what you keep:
61
62```go
63name := strings.Clone(r.Str())
64icon := bytes.Clone(r.ByteArray())
65```
66
67## Receive signals
68
69```go
70c.AddMatch("type='signal',interface='org.kde.StatusNotifierItem'")
71for {
72 m, err := c.ReadMessage()
73 if err != nil {
74 return err
75 }
76 if m.Type == zerobus.TypeSignal {
77 fmt.Println(m.Sender, m.Member)
78 }
79}
80```
81
82`Call` reads messages until its reply arrives. Set `Conn.Handle` to receive the messages that arrive meanwhile; they are dropped otherwise. `Handle` may send (answer a call, emit a signal), but not wait: `Call` and `ReadMessage` return `ErrNested` inside it.
83
84## Answer calls
85
86```go
87c.RequestName("org.example.Echo", zerobus.NameFlagDoNotQueue)
88for {
89 m, err := c.ReadMessage()
90 if err != nil {
91 return err
92 }
93 if m.Type == zerobus.TypeMethodCall && m.Member == "Echo" {
94 c.NewReply(m, "s").Str(m.Body().Str())
95 c.Send()
96 }
97}
98```
99
100## Concurrency
101
102A `Conn` is not safe for concurrent use. Use it from one goroutine, usually an event loop around `ReadMessage`. `Close` may be called from any goroutine: a blocked `ReadMessage` then returns `ErrClosed`.
103
104## Not supported
105
106- Transports other than `unix:path` and `unix:abstract` (no TCP, no `launchd`, no `autolaunch`).
107- Passing file descriptors (`UNIX_FD` values can be read, but no descriptors are received).
108- Authentication other than `EXTERNAL`.
109- Reflection-based marshalling, introspection and code generation.
110
111## Example
112
113[`examples/trayitems`](examples/trayitems) lists the system tray items on the session bus and prints their changes.
114
115## License
116
117MIT