Publish/Subscribe API for Go SDK
PubNub delivers messages worldwide in less than 30 ms. Send a message to one recipient or broadcast to thousands of subscribers.
For higher-level conceptual details on publishing and subscribing, refer to Connection Management and to Publish Messages.
Publish
The Publish() method sends a message to all channel subscribers. PubNub replicates the message across its points of presence and delivers it to all subscribed clients on that channel.
- Prerequisites and limitations
- Security
- Message data
- Size
- Publish rate
- Custom message type
- Best practices
- You must initialize PubNub with the
publishKey. - You don't have to be subscribed to a channel to publish to it.
- You cannot publish to multiple channels simultaneously.
Secure messages with Transport Layer Security (TLS) or Secure Sockets Layer (SSL) by setting ssl to true during initialization. You can also encrypt messages.
The message can contain any JavaScript Object Notation (JSON)-serializable data (objects, arrays, integers, strings). Avoid special classes or functions. Strings can include any UTF‑8 characters.
Don't JSON serialize
You should not JSON serialize the message and meta parameters when sending signals, messages, or files as the serialization is automatic. Pass the full object as the message/meta payload and let PubNub handle everything.
The maximum message size is 32 KiB. This includes the escaped character count and the channel name. Aim for under 1,800 bytes for optimal performance.
If your message exceeds the limit, you'll receive a Message Too Large error. To learn more or calculate payload size, see Message size limits.
You can publish as fast as bandwidth allows. There is a soft throughput limit because messages may drop if subscribers can't keep up.
For example, publishing 200 messages at once may cause the first 100 to drop if a subscriber hasn't received any yet. The in-memory queue stores only 100 messages.
You can optionally provide the CustomMessageType parameter to add your business-specific label or category to the message, for example text, action, or poll.
- Publish to a channel serially (not concurrently).
- Verify a success return code (for example,
[1,"Sent","136074940..."]). - Publish the next message only after a success return code.
- On failure (
[0,"blah","<timetoken>"]), retry. - Keep the in-memory queue under 100 messages to avoid drops.
- Throttle bursts to meet latency needs (for example, no more than 5 messages per second).
Method(s)
To Publish a message you can use the following method(s) in the Go SDK:
pn.Publish().
Message(interface{}).
Channel(string).
ShouldStore(bool).
UsePost(bool).
Meta(interface{}).
QueryParam(queryParam).
CustomMessageType(string).
Execute()
| Parameter | Description |
|---|---|
Message *Type: interface Default: n/a | The payload |
Channel *Type: string Default: n/a | Destination of Message (channel ID) |
ShouldStoreType: bool Default: account default | Store in history |
UsePostType: bool Default: false | Use POST to Publish |
MetaType: interface Default: null | Meta data object which can be used with the filtering ability |
TTLType: int Default: n/a | Set a per message time to live in Message Persistence.
|
QueryParamType: map[string]string Default: nil | QueryParam accepts a map, the keys and values of the map are passed as the query string parameters of the URL called by the API. |
CustomMessageTypeType: string Default: n/a | A case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes - and underscores _ are allowed. The value cannot start with special characters or the string pn_ or pn-. Examples: text, action, poll. |
Sample code
Reference code
Publish a message to a channel
package main
import (
"fmt"
pubnub "github.com/pubnub/go/v7"
)
func main() {
config := pubnub.NewConfigWithUserId("myUniqueUserId")
config.SubscribeKey = "demo"
config.PublishKey = "demo"
pn := pubnub.NewPubNub(config)
message := []string{"Hello", "there"}
show all 31 linesSubscribe to the channel
Before running the above publish example, either using the Debug Console or in a separate script running in a separate terminal window, subscribe to the same channel that is being published to.
Response
| Method | Description |
|---|---|
TimestampType: int | An int representation of the timetoken when the message was published |
Other examples
Publish with metadata
res, status, err := pn.Publish().
Channel("my-channel").
Message([]string{"Hello", "there"}).
Meta(map[string]interface{}{
"name": "Alex",
}).
CustomMessageType("text-message").
Execute()
Publish array
res, status, err := pn.Publish().
Channel("my-channel").
Message([]string{"Hello", "there"}).
Meta([]string{"1a", "2b", "3c"}).
CustomMessageType("text-message").
Execute()
Store the published message for 10 hours
res, status, err := pn.Publish().
Channel("my-channel").
Message("test").
ShouldStore(true).
TTL(10).
CustomMessageType("text-message").
Execute()
Push payload helper
You can use the helper method as an input to the Message parameter, to format the payload for publishing Push messages. For more info on the helper method, check Create Push Payload Helper Section
aps := pubnub.PNAPSData{
Alert: "apns alert",
Badge: 1,
Sound: "ding",
Custom: map[string]interface{}{
"aps_key1": "aps_value1",
"aps_key2": "aps_value2",
},
}
apns := pubnub.PNAPNSData{
APS: aps,
Custom: map[string]interface{}{
"apns_key1": "apns_value1",
"apns_key2": "apns_value2",
show all 82 linesFire
The fire endpoint sends a message to Functions event handlers and Illuminate. The message goes directly to handlers registered on the target channel and triggers their execution. The handler can read the request body. Messages sent via fire() aren't replicated to subscribers and aren't stored in history.
Method(s)
To Fire a message you can use the following method(s) in the Go SDK:
pn.Fire().
Message(interface{}).
Channel(string).
UsePost(bool).
Meta(interface{}).
QueryParam(queryParam).
Execute()
| Parameter | Description |
|---|---|
Message *Type: interface Default: n/a | The payload |
Channel *Type: string Default: n/a | Destination of Message (channel ID) |
UsePostType: bool Default: false | Use POST to Publish |
MetaType: interface Default: null | Meta data object which can be used with the filtering ability |
TTLType: int Default: n/a | Set a per message time to live in Message Persistence.
|
QueryParamType: map[string]string Default: nil | QueryParam accepts a map, the keys and values of the map are passed as the query string parameters of the URL called by the API. |
Sample code
Fire a message to a channel
res, status, err := pn.Fire().
Channel("my-channel").
Message("test").
Execute()
Signal
The signal() function sends a signal to all subscribers of a channel.
By default, signals are limited to a message payload size of 64 bytes. This limit applies only to the payload, and not to the URI or headers. If you require a larger payload size, please contact support.
Method(s)
To Signal a message you can use the following method(s) in the Go SDK:
pubnub.Signal().
Message(interface{}).
Channel(string).
CustomMessageType(string).
Execute()
| Parameter | Description |
|---|---|
Message *Type: interface Default: n/a | The payload. |
Channel *Type: string Default: n/a | Destination of Message (channel ID). |
CustomMessageTypeType: string Default: n/a | A case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes - and underscores _ are allowed. The value cannot start with special characters or the string pn_ or pn-. Examples: text, action, poll. |
Sample code
Signal a message to a channel
result, status, err := pubnub.Signal().
Message([]string{
"Hello", "Signals"
}).
Channel("foo").
CustomMessageType("text-message").
Execute();
Response
| Method | Description |
|---|---|
TimestampType: int | An int representation of the timetoken when Signal was sent |
Subscribe
Receive messages
Your app receives messages and events via event listeners. The event listener is a single point through which your app receives all the messages, signals, and events that are sent in any channel you are subscribed to.
For more information about adding a listener, refer to the Event Listeners section.
Description
This function causes the client to create an open TCP socket to the PubNub Real-Time Network and begin listening for messages on a specified channel ID. To subscribe to a channel ID the client must send the appropriate SubscribeKey at initialization. By default a newly subscribed client will only receive messages published to the channel after the Subscribe() call completes.
Connectivity notification
You can be notified of connectivity via the envelope.status. By waiting for the envelope.status to return before attempting to publish, you can avoid a potential race condition on clients that subscribe and immediately publish messages before the subscribe has completed.
Using Go SDK, if a client becomes disconnected from a channel, it can automatically attempt to reconnect to that channel and retrieve any available messages that were missed during that period by setting restore to true. By default a client will attempt to reconnect after exceeding a 320 second connection timeout.
Unsubscribing from all channels
Unsubscribing from all channels, and then subscribing to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously-subscribed channel(s). Unsubscribing from all channels resets the last-received timetoken and thus, there could be some gaps in the subscription that may lead to message loss.
Method(s)
To Subscribe to a channel you can use the following method(s) in the Go SDK:
pn.Subscribe().
Channels([]string).
ChannelGroups([]string).
Timetoken(int64).
WithPresence(bool).
QueryParam(queryParam).
Execute()
| Parameter | Description |
|---|---|
ChannelsType: []string | Subscribe to channels, Either channel ID or channel_group is required. |
ChannelGroupsType: []string | Subscribe to channel_groups, Either channel ID or channel_group is required. |
TimetokenType: int64 | Pass a timetoken. |
WithPresenceType: bool | Also subscribe to related presence information. For information on how to receive presence events and what those events are, refer to Presence Events. |
QueryParamType: map[string]string | QueryParam accepts a map, the keys and values of the map are passed as the query string parameters of the URL called by the API. |
Sample code
Subscribe to a channel:
pn.Subscribe().
Channels([]string{"my-channel"}). // subscribe to channels
Execute()
Response
PNMessage
PNMessage is returned in the Listeners
The Subscribe() operation returns a PNStatus which contains the following operations:
| Property Name | Type | Description |
|---|---|---|
Category | StatusCategory | See the Go SDK listener categories. |
Error | bool | This is true if an error occurred in the execution of the operation. |
ErrorData | error | Error data of the exception (if Error is true). |
StatusCode | int | Status code of the execution. |
Operation | OperationType | Operation type of the request. |
The Subscribe() operation returns a PNMessage for messages, for both Publish and Signal messages, which contains the following operations:
| Method | Description |
|---|---|
MessageType: interface | The message sent on the channel ID. |
ChannelType: string | The channel ID on which the message was received. |
SubscriptionType: string | The channel group or wildcard subscription match (if exists). |
TimetokenType: int64 | Timetoken for the message. |
UserMetadataType: interface | User metadata. |
SubscribedChannelType: string | Current subscribed channel. |
PublisherType: string | UUID of publisher. |
The Subscribe() operation returns a PNPresence for messages which contains the following operations:
| Method | Description |
|---|---|
EventType: string | Events like join, leave, timeout, state-change. |
UUIDType: string | UUID for event. |
TimestampType: int64 | Timestamp for event. |
OccupancyType: int | Current occupancy. |
SubscriptionType: string | Message has been received on the Channel ID. |
TimetokenType: int64 | Timetoken of the message. |
StateType: interface | State of the UUID. |
UserMetadataType: map[string]interface | User metadata. |
SubscribedChannelType: string | Current subscribed channel. |
ChannelType: string | The channel ID for which the message belongs. |
The Subscribe() operation returns a PNUUIDEvent for UUID Events which contains the following operations:
| Method | Description |
|---|---|
EventType: PNObjectsEvent | Events like PNObjectsEventRemove, PNObjectsEventSet. |
TimestampType: string | Timestamp for event. |
SubscriptionType: string | Event has been received on the Channel ID. |
SubscribedChannelType: string | Current subscribed channel. |
ChannelType: string | The channel ID for which the event belongs. |
UUIDType: string | The UUID. |
NameType: string | Display name for the space. |
ExternalIDType: string | User's identifier in an external system |
ProfileURLType: string | The URL of the user's profile picture |
EmailType: string | The user's email address. |
CustomType: map[string]interface | Map of string and interface with supported data types. |
UpdatedType: string | Last updated date. |
ETagType: string | The ETag. |
The Subscribe() operation returns a PNChannelEvent for Channel Events which contains the following operations:
| Method | Description |
|---|---|
EventType: PNObjectsEvent | Events like PNObjectsEventRemove, PNObjectsEventSet. |
TimestampType: string | Timestamp for event. |
SubscriptionType: string | Event has been received on the Channel ID. |
SubscribedChannelType: string | Current subscribed channel. |
ChannelType: string | The channel ID for which the event belongs. |
ChannelIDType: string | The Channel ID. |
NameType: string | Display name for the space. |
DescriptionType: string | Description of the space. |
CustomType: map[string]interface | Map of string and interface with supported data types. |
UpdatedType: string | Last updated date. |
ETagType: string | The ETag. |
The Subscribe() operation returns a PNMembershipEvent for Membership Events which contains the following operations:
| Method | Description |
|---|---|
EventType: PNObjectsEvent | Events like PNObjectsEventRemove, PNObjectsEventSet. |
TimestampType: string | Timestamp for event. |
SubscriptionType: string | Event has been received on the Channel ID. |
SubscribedChannelType: string | Current subscribed channel. |
ChannelType: string | The channel ID for which the event belongs. |
ChannelIDType: string | The Channel ID. |
UUIDType: string | The UUID. |
CustomType: map[string]interface | Map of string and interface with supported data types. |
The Subscribe() operation returns a PNMessageActionsEvent for Message Actions Events which contains the following operations:
| Method | Description |
|---|---|
EventType: PNMessageActionsEventType | Events like PNMessageActionsAdded, PNMessageActionsRemoved. |
DataType: PNMessageActionsResponse | Message Actions for event. |
SubscriptionType: string | Event has been received on the Channel ID. |
SubscribedChannelType: string | Current subscribed channel. |
ChannelType: string | The channel ID for which the event belongs. |
Other examples
Basic subscribe with logging
import (
pubnub "github.com/pubnub/go"
)
config := pubnub.NewConfig()
// publishKey from admin panel (only required if publishing)
config.PublishKey = "demo" // required
// subscribeKey from admin panel
config.SubscribeKey = "demo"
pn := pubnub.NewPubNub(config)
pn.Subscribe().
Channels([]string{"my-channel"}).
Execute()
Subscribing to multiple channels
It's possible to subscribe to more than one channel using the Multiplexing feature. The example shows how to do that using an array to specify the channel names.
Alternative subscription methods
You can also use Wildcard Subscribe and Channel Groups to subscribe to multiple channels at a time. To use these features, the Stream Controller add-on must be enabled on your keyset in the Admin Portal.
import (
pubnub "github.com/pubnub/go"
)
pn.Subscribe().
Channels([]string{"my-channel1", "my-channel2"}).
Execute()
Subscribing to a Presence channel
Requires Presence
This method requires that the Presence add-on is enabled for your key in the Admin Portal.
For information on how to receive presence events and what those events are, refer to Presence Events.
For any given channel there is an associated Presence channel. You can subscribe directly to the channel by appending -pnpres to the channel name. For example the channel named my_channel would have the presence channel named my_channel-pnpres.
pn.Subscribe().
Channels([]string{"my-channel"}).
WithPresence(true).
Execute()
Sample Responses
Join event
if presence.Event == "join" {
presence.UUID // 175c2c67-b2a9-470d-8f4b-1db94f90e39e
presence.Timestamp // 1345546797
presence.Occupancy // 2
}
Leave event
if presence.Event == "leave" {
presence.UUID // 175c2c67-b2a9-470d-8f4b-1db94f90e39e
presence.Timestamp // 1345546797
presence.Occupancy // 2
}
Timeout event
if presence.Event == "timeout" {
presence.UUID // 175c2c67-b2a9-470d-8f4b-1db94f90e39e
presence.Timestamp // 1345546797
presence.Occupancy // 2
}
State change event
if presence.Event == "state-change" {
presence.Timestamp
presence.Occupancy
}
Interval event
if presence.Event == "interval" {
presence.UUID // 175c2c67-b2a9-470d-8f4b-1db94f90e39e
presence.Timestamp // 1345546797
presence.Occupancy // 2
}
When a channel is in interval mode with presence_deltas pnconfig flag enabled, the interval message may also include the following fields which contain an array of changed UUIDs since the last interval message.
- joined
- left
- timedout
For example, this interval message indicates there were 2 new UUIDs that joined and 1 timed out UUID since the last interval:
if presence.Event == "interval" {
presence.Occupancy // # users in channel
presence.Join // [uuid1 uuid2]
presence.Timeout //[uuid3]
presence.Timestamp // unix timestamp
}
If the full interval message is greater than 30KB (since the max publish payload is ∼32KB), none of the extra fields will be present. Instead there will be a here_now_refresh boolean field set to true. This indicates to the user that they should do a hereNow request to get the complete list of users present in the channel.
Wildcard subscribe to channels
Requires Stream Controller add-on
This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal (with Enable Wildcard Subscribe checked). Read the support page on enabling add-on features on your keys.
Wildcard subscribes allow the client to subscribe to multiple channels using wildcard. For example, if you subscribe to a.* you will get all messages for a.b, a.c, a.x. The wildcarded * portion refers to any portion of the channel string name after the dot (.).
import (
pubnub "github.com/pubnub/go"
)
pn.Subscribe().
Channels([]string{"foo.*"}). // subscribe to channels information
Execute()
Wildcard grants and revokes
Only one level (a.*) of wildcarding is supported. If you grant on * or a.b.*, the grant will treat * or a.b.* as a single channel named either * or a.b.*. You can also revoke permissions from multiple channels using wildcards but only if you previously granted permissions using the same wildcards. Wildcard revokes, similarly to grants, only work one level deep, like a.*.
Subscribing with state
Requires Presence
This method requires that the Presence add-on is enabled for your key in the Admin Portal.
For information on how to receive presence events and what those events are, refer to Presence Events.
Required UUID
Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.
import (
pubnub "github.com/pubnub/go"
)
config := pubnub.NewConfig()
config.SubscribeKey = "demo"
config.PublishKey = "demo"
pn := pubnub.NewPubNub(config)
listener := pubnub.NewListener()
done := make(chan bool)
go func() {
for {
show all 45 linesSubscribe to a channel group
Requires Stream Controller add-on
This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
import (
pubnub "github.com/pubnub/go"
)
pn.Subscribe().
Channels([]string{"ch1", "ch2"}). // subscribe to channels
ChannelGroups([]string{"cg1", "cg2"}). // subscribe to channel groups
Timetoken(int64(1337)). // optional, pass a timetoken
WithPresence(true). // also subscribe to related presence information
Execute()
Subscribe to the Presence channel of a channel group
Requires Stream Controller and Presence add-ons
This method requires both the Stream Controller and Presence add-ons are enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
import (
pubnub "github.com/pubnub/go"
)
pn.Subscribe().
ChannelGroups([]string{"cg1", "cg2"}). // subscribe to channel groups
Timetoken(int64(1337)). // optional, pass a timetoken
WithPresence(true). // also subscribe to related presence information
Execute()
Unsubscribe
When subscribed to a single channel, this function causes the client to issue a leave from the channel and close any open socket to the PubNub Network. For multiplexed channels, the specified channel(s) will be removed and the socket remains open until there are no more channels remaining in the list.
Unsubscribing from all channels
Unsubscribing from all channels, and then subscribing to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously-subscribed channel(s). Unsubscribing from all channels resets the last-received timetoken and thus, there could be some gaps in the subscription that may lead to message loss.
Method(s)
To Unsubscribe from a channel you can use the following method(s) in the Go SDK:
pn.Unsubscribe().
Channels([]string).
ChannelGroups([]string).
QueryParam(queryParam).
Execute()
| Parameter | Description |
|---|---|
ChannelsType: []string Default: false | Unsubscribe to channels, Either channel ID or channelGroup is required. |
ChannelGroupsType: []string Default: false | Unsubscribe to channel groups, Either channel ID or channelGroup is required. |
QueryParamType: map[string]string Default: nil | QueryParam accepts a map, the keys and values of the map are passed as the query string parameters of the URL called by the API. |
Sample code
Unsubscribe from a channel:
pn.Unsubscribe().
Channels([]string{"my-channel"}).
Execute()
Event listeners
The response of the subscription is handled by Listener. Please see the Listeners section for more details.
Rest response from server
The output below demonstrates the response to a successful call:
if presence.Event == "leave" {
presence.UUID // left-uuid
presence.Timestamp // 1345546797
presence.Occupancy // 2
}
Other examples
Unsubscribing from multiple channels
Requires Stream Controller add-on
This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
import (
pubnub "github.com/pubnub/go"
)
pn.Unsubscribe().
Channels([]string{"my-channel", "my-channel2"}).
Execute()
Example response
if presence.Event == "leave" {
presence.UUID // left-uuid
presence.Timestamp // 1345546797
presence.Occupancy // 2
}
Unsubscribe from a channel group
import (
pubnub "github.com/pubnub/go"
)
pn.Unsubscribe().
ChannelGroups([]string{"cg1", "cg2"}).
Execute()
if presence.Event == "leave" {
presence.UUID // left-uuid
presence.Timestamp // 1345546797
presence.Occupancy // 2
}
Unsubscribe all
Unsubscribe from all channels and all channel groups
Method(s)
UnsubscribeAll()
Sample code
pn.UnsubscribeAll()
Returns
None