Categorygithub.com/psytale/go
modulepackage
4.10.0+incompatible
Repository: https://github.com/psytale/go.git
Documentation: pkg.go.dev

# README

PubNub Go SDK

GoDoc Build Status codecov.io Go Report Card

This is the official PubNub Go SDK repository.

PubNub takes care of the infrastructure and APIs needed for the realtime communication layer of your application. Work on your app's logic and let PubNub handle sending and receiving data across the world in less than 100ms.

Requirements

  • Go (1.9+)

Get keys

You will need the publish and subscribe keys to authenticate your app. Get your keys from the Admin Portal.

Configure PubNub

  1. Integrate PubNub into your project using the go command:

    go get github.com/pubnub/go
    

    If you encounter dependency issues, use the dep ensure command to resolve them.

  2. Create a new file and add the following code:

    func main() {
        config := pubnub.NewConfig()
        config.SubscribeKey = "mySubscribeKey"
        config.PublishKey = "myPublishKey"
        config.UUID = "myUniqueUUID"
    
        pn := pubnub.NewPubNub(config)
    }
    

Add event listeners

listener := pubnub.NewListener()
doneConnect := make(chan bool)
donePublish := make(chan bool)

msg := map[string]interface{}{
    "msg": "Hello world",
}
go func() {
    for {
        select {
        case status := <-listener.Status:
            switch status.Category {
            case pubnub.PNDisconnectedCategory:
                // This event happens when radio / connectivity is lost
            case pubnub.PNConnectedCategory:
                // Connect event. You can do stuff like publish, and know you'll get it.
                // Or just use the connected event to confirm you are subscribed for
                // UI / internal notifications, etc
                doneConnect <- true
            case pubnub.PNReconnectedCategory:
                // Happens as part of our regular operation. This event happens when
                // radio / connectivity is lost, then regained.
            }
        case message := <-listener.Message:
            // Handle new message stored in message.message
            if message.Channel != "" {
                // Message has been received on channel group stored in
                // message.Channel
            } else {
                // Message has been received on channel stored in
                // message.Subscription
            }
            if msg, ok := message.Message.(map[string]interface{}); ok {
                fmt.Println(msg["msg"])
            }
            /*
                log the following items with your favorite logger
                    - message.Message
                    - message.Subscription
                    - message.Timetoken
            */

            donePublish <- true
        case <-listener.Presence:
            // handle presence
        }
    }
}()

pn.AddListener(listener)

Publish and subscribe

In this code, publishing a message is triggered when the subscribe call is finished successfully. The Publish() method uses the msg variable that is used in the following code.

msg := map[string]interface{}{
        "msg": "Hello world!"
}

pn.Subscribe().
    Channels([]string{"hello_world"}).
    Execute()

<-doneConnect

response, status, err := pn.Publish().
    Channel("hello_world").Message(msg).Execute()

if err != nil {
     // Request processing failed.
     // Handle message publish error
}

Documentation

API reference for Go

Support

If you need help or have a general question, contact [email protected].

# Packages

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Functions

EnumArrayToStringArray converts a string enum to an array.
GetPermissions decodes the CBORToken.
NewConfig initiates the config with default values.
NewDemoConfig initiates the config with demo keys, for tests only.
NewHTTP1Client creates a new HTTP 1 client with a new transport initialized with connect and read timeout.
NewHTTP2Client creates a new HTTP 2 client with a new transport initialized with connect and read timeout.
NewListener initates the listener to facilitate the event handling.
NewPubNub instantiates a PubNub instance with default values.
NewPubNubDemo returns an instance with demo keys.
ParseFileInfo is a function extract file info and add to the struct PNFileMessageAndDetails.
ParseGrantResources parses the token for permissions and adds them along the other values to the GrantResourcesWithPermissions struct.
SetArrayTypeQueryParam appends to the query string the key val pair.
SetPushEnvironment appends the push environment to the query string.
SetPushTopic appends the topic to the query string.
SetQueryParam appends the query params map to the query string.
SetQueryParamAsCommaSepString appends to the query string the comma separated string.

# Constants

MaxSequence for publish messages.
PNAccessDeniedCategory as the StatusCategory means that PAM is enabled and the channel is not granted R/W access.
PNAccessManagerGrant is the enum used for the Access Manager Grant operation.
PNAccessManagerGrantToken is the enum used for Grant v3 requests.
PNAccessManagerRevoke is the enum used for the Access Manager Revoke operation.
PNAcknowledgmentCategory as the StatusCategory is the Acknowledgement of an operation (like Unsubscribe).
PNAddChannelsToChannelGroupOperation is the enum used for the Add Channels to Channel Group operation.
PNAddMessageActionsOperation is the enum used for Message Actions Add requests.
PNAddPushNotificationsOnChannelsOperation is the enum used for the Add Channels to Push Notifications operation.
PNBadRequestCategory as the StatusCategory means the request was malformed.
PNCancelledCategory as the StatusCategory means the context was cancelled.
PNChannelMembersIncludeCustom is the enum equivalent to the value `custom` available Members include types.
PNChannelMembersIncludeUUID is the enum equivalent to the value `uuid` available Members include types.
PNChannelMembersIncludeUUIDCustom is the enum equivalent to the value `uuid.custom` available Members include types.
PNChannelMetadataIncludeCustom is the enum equivalent to the value `custom` available Channel include types.
PNChannels for channels.
PNChannelsForGroupOperation is the enum used for the List Channels of Channel Group operation.
PNConnectedCategory as the StatusCategory means the channel is subscribed to receive messages.
PNCreate Create Perms.
PNCreateEnabled Create Enabled.
PNCreateSpaceOperation is the enum used to create space in the Object API.
PNCreateUserOperation is the enum used to create users in the Object API.
PNDelete Delete Perms.
PNDeleteEnabled Delete Enabled.
PNDeleteFileOperation is the enum used for DeleteFile requests.
PNDeleteMessagesOperation is the enum used for the Delete Messages from History operation.
PNDeleteSpaceOperation is the enum used to delete space in the Object API.
PNDeleteUserOperation is the enum used to delete users in the Object API.
PNDisconnectedCategory as the StatusCategory means a disconnection occurred due to network issues.
PNDownloadFileOperation is the enum used for DownloadFile requests.
PNExponentialPolicy is to be used when selecting the Exponential Reconnection Policy ReconnectionPolicy is set in the config.
PNFetchMessagesOperation is the enum used for the Fetch operation.
PNFireOperation is the enum used for the Fire operation.
PNGetAllChannelMetadataOperation is the enum used to Get All Channel Metadata in the Object API.
PNGetAllUUIDMetadataOperation is the enum used to Get All UUID Metadata in the Object API.
PNGetChannelMembersOperation is the enum used to get members in the Object API.
PNGetChannelMetadataOperation is the enum used to Get Channel Metadata in the Object API.
PNGetEnabled Get Enabled.
PNGetFileURLOperation is the enum used for GetFileURL requests.
PNGetMembershipsOperation is the enum used to get memberships in the Object API.
PNGetMessageActionsOperation is the enum used for Message Actions Get requests.
PNGetSpaceOperation is the enum used to get space in the Object API.
PNGetSpacesOperation is the enum used to get spaces in the Object API.
PNGetStateOperation is the enum used for the Get State operation.
PNGetUserOperation is the enum used to get user in the Object API.
PNGetUsersOperation is the enum used to get users in the Object API.
PNGetUUIDMetadataOperation is the enum used to Get UUID Metadata in the Object API.
PNGroups for groups.
PNHeartBeatOperation is the enum used for the Heartbeat operation.
PNHereNowOperation is the enum used for the Here Now operation.
PNHistoryOperation is the enum used for the History operation.
PNHistoryWithActionsOperation is the enum used for History with Actions requests.
PNJoinEnabled Join Enabled.
PNLinearPolicy is to be used when selecting the Linear Reconnection Policy ReconnectionPolicy is set in the config.
PNListFilesOperation is the enum used for ListFiles requests.
PNLoopStopCategory as the StatusCategory means the subscribe loop was stopped.
PNManage Manage Perms.
PNManageEnabled Manage Enabled.
PNManageMembershipsOperation is the enum used to manage memberships in the Object API.
PNManageMembersOperation is the enum used to manage members in the Object API.
PNMembershipsIncludeChannel is the enum equivalent to the value `channel` available Memberships include types.
PNMembershipsIncludeChannelCustom is the enum equivalent to the value `channel.custom` available Memberships include types.
PNMembershipsIncludeCustom is the enum equivalent to the value `custom` available Memberships include types.
PNMessageActionsAdded is the enum when the event of type `added` occurs.
PNMessageActionsRemoved is the enum when the event of type `removed` occurs.
PNMessageCountsOperation is the enum used for History with messages operation.
PNMessageTypeFile is to identify Files the Subscribe response.
PNMessageTypeMessageActions is to identify Actions the Subscribe response.
PNMessageTypeObjects is to identify Objects the Subscribe response.
PNMessageTypeSignal is to identify Signal the Subscribe response.
PNNonePolicy is to be used when selecting the no Reconnection Policy ReconnectionPolicy is set in the config.
PNNoStubMatchedCategory as the StatusCategory means an unknown status category event occurred.
PNObjectsChannelEvent is the enum when the event of type `channel` occurs.
PNObjectsEventRemove is the enum when the event `delete` occurs.
PNObjectsEventSet is the enum when the event `set` occurs.
PNObjectsMembershipEvent is the enum when the event of type `membership` occurs.
PNObjectsNoneEvent is used for error handling.
PNObjectsUUIDEvent is the enum when the event of type `uuid` occurs.
PNPublishFileMessageOperation is the enum used for PublishFileMessage requests.
PNPublishOperation is the enum used for the Publish operation.
PNPushEnvironmentDevelopment for development.
PNPushEnvironmentProduction for production.
PNPushNotificationsEnabledChannelsOperation is the enum used for the List Channels with Push Notifications enabled operation.
PNPushTypeAPNS is used as an enum to for selecting `APNS` as the PNPushType.
PNPushTypeAPNS2 is used as an enum to for selecting `APNS2` as the PNPushType.
PNPushTypeGCM is used as an enum to for selecting `GCM` as the PNPushType.
PNPushTypeMPNS is used as an enum to for selecting `MPNS` as the PNPushType.
PNPushTypeNone is used as an enum to for selecting `none` as the PNPushType.
PNRead Read Perms.
PNReadEnabled Read Enabled.
PNReconnectedCategory as the StatusCategory means that the network was reconnected (after a disconnection).
PNReconnectionAttemptsExhausted as the StatusCategory means that the reconnection attempts to reconnect to the network were exhausted.
PNRemoveAllPushNotificationsOperation is the enum used for the Remove All Channels from Push Notifications operation.
PNRemoveChannelFromChannelGroupOperation is the enum used for the Remove Channels from Channel Group operation.
PNRemoveChannelMembersOperation is the enum used to Remove Members in the Object API.
PNRemoveChannelMetadataOperation is the enum used to Remove Channel Metadata in the Object API.
PNRemoveGroupOperation is the enum used for the Remove Channel Group operation.
PNRemoveMembershipsOperation is the enum used to Remove Memberships in the Object API.
PNRemoveMessageActionsOperation is the enum used for Message Actions Remove requests.
PNRemovePushNotificationsFromChannelsOperation is the enum used for the Remove Channels from Push Notifications operation.
PNRemoveUUIDMetadataOperation is the enum used to Remove UUID Metadata in the Object API.
PNRequestMessageCountExceededCategory is fired when the MessageQueueOverflowCount limit is exceeded by the number of messages received in a single subscribe request.
PNSendFileOperation is the enum used for SendFile requests.
PNSendFileToS3Operation is the enum used for v requests.
PNSetChannelMembersOperation is the enum used to Set Members in the Object API.
PNSetChannelMetadataOperation is the enum used to Set Channel Metadata in the Object API.
PNSetMembershipsOperation is the enum used to Set Memberships in the Object API.
PNSetStateOperation is the enum used for the Set State operation.
PNSetUUIDMetadataOperation is the enum used to Set UUID Metadata in the Object API.
PNSignalOperation is the enum used for Signal opertaion.
PNSpaces for spaces.
PNSubscribeOperation is the enum used for the Subcribe operation.
PNTimeOperation is the enum used for the Time operation.
PNTimeoutCategory as the StatusCategory means the request timeout has reached.
PNUnknownCategory as the StatusCategory means an unknown status category event occurred.
PNUnsubscribeOperation is the enum used for the Unsubcribe operation.
PNUpdateEnabled Update Enabled.
PNUpdateSpaceOperation is the enum used to update space in the Object API.
PNUpdateUserOperation is the enum used to update users in the Object API.
PNUsers for users.
PNUUIDMetadataIncludeCustom is the enum equivalent to the value `custom` available UUID include types.
PNWhereNowOperation is the enum used for the Where Now operation.
PNWrite Write Perms.
PNWriteEnabled Write Enabled.
StrChannelsTimetoken shows Missing Channels Timetoken message.
StrChannelsTimetokenLength shows Length of Channels Timetoken message.
StrInvalidTTL shows Invalid TTL message.
StrMissingChannel shows Channel message.
StrMissingChannelGroup shows Channel Group message.
StrMissingDeviceID shows Missing Device ID message.
StrMissingFileID shows `Missing File ID` message.
StrMissingFileName shows `Missing File Name` message.
StrMissingMessage shows Missing Message message.
StrMissingPubKey shows Missing Publish Key message.
StrMissingPushTitle shows `Push title missing` message.
StrMissingPushTopic shows Missing Push Topic message.
StrMissingPushType shows Missing Push Type message.
StrMissingSecretKey shows Missing Secret Key message.
StrMissingSubKey shows Missing Subscribe Key message.
StrMissingUUID shows Missing UUID message.
Version :the version of the SDK.

# Structs

AddChannelToChannelGroupResponse is the struct returned when the Execute function of AddChannelToChannelGroup is called.
AddPushNotificationsOnChannelsResponse is response structure for AddPushNotificationsOnChannelsBuilder.
AllChannelGroupResponse is the struct returned when the Execute function of List All Channel Groups is called.
ChannelPermissions contains all the acceptable perms for channels.
ChannelPermissionsWithToken is used for channels resource type permissions.
Config instance is storage for user-provided information which describe further PubNub client behaviour.
DeleteChannelGroupResponse is response structure for Delete Channel Group function.
FetchResponse is the response to Fetch request.
FetchResponseItem contains the message and the associated timetoken.
GetStateResponse is the struct returned when the Execute function of GetState is called.
GrantResources is the struct used to decode the server response.
GrantResourcesWithPermissions is used as a common struct to store all resource type permissions.
GrantResponse is the struct returned when the Execute function of Grant is called.
GroupPermissions contains all the acceptable perms for groups.
GroupPermissionsWithToken is used for groups resource type permissions.
HeartbeatManager is a struct that assists in running of the heartbeat.
HereNowChannelData is the struct containing the occupancy details of the channels.
HereNowOccupantsData is the struct containing the state and UUID of the occupants in the channel.
HereNowResponse is the struct returned when the Execute function of HereNow is called.
HistoryDeleteResponse is the struct returned when Delete Messages is called.
HistoryResponse is used to store the response from the History request.
HistoryResponseItem is used to store the Message and the associated timetoken from the History request.
JobQItem is the type to store the request, client and its resposne.
JobQResponse is the type to store the resposne and error of the requests in the queue.
LatencyEntry is the struct to store the timestamp and latency values.
Listener type has all the `types` of response events.
ListenerManager is used in the internal handling of listeners.
ListPushProvisionsRequestResponse is the struct returned when the Execute function of ListPushProvisions is called.
MessageAction struct is used to create a Message Action.
MessageCountsResponse is the response to MessageCounts request.
Operations is the struct to store the latency values of different operations.
PermissionsBody is the struct used to decode the server response.
PNAccessManagerKeyData is the struct containing the access details of the channel groups.
PNAddMessageActionsResponse is the Add Message Actions API Response.
PNAPNS2Data is the struct used for the APNS2 paylod.
PNAPNSData is the struct used for the APNS paylod.
PNAPSData is the helper struct used for the APNS paylod.
PNChannel is the Objects API space struct.
PNChannelEvent is the Response for a Space Event.
PNChannelMembers is the Objects API Members struct.
PNChannelMembersRemove is the Objects API Members struct used to remove members.
PNChannelMembersRemoveChangeset is the Objects API input to add, remove or update membership.
PNChannelMembersSet is the Objects API Members input struct used to add members.
PNChannelMembersSetChangeset is the Objects API input to add, remove or update membership.
PNChannelMembersUUID is the Objects API Members input struct used to add members.
PNDeleteFileResponse is the File Upload API Response for Delete file operation.
PNDownloadFileResponse is the File Upload API Response for Get Spaces.
PNFCMData is the struct used for the FCM paylod.
PNFCMDataFields is the helper struct used for the FCM paylod.
PNFileData is used in the responses to show File ID.
PNFileDetails is used in the responses to show File Info.
PNFileInfo is the File Upload API struct returned on for each file.
PNFileInfoForPublish is the part of the message struct used in Publish File.
PNFileMessageAndDetails is used to store the file message and file info.
PNFilesEvent is the Response for a Files Event.
PNFileUploadRequest is used to store the info related to file upload to S3.
PNFormField is part of the struct used in file upload to S3.
PNGetAllChannelMetadataResponse is the Objects API Response for Get Spaces.
PNGetAllUUIDMetadataResponse is the Objects API Response for Get Users.
PNGetChannelMembersResponse is the Objects API Response for Get Members.
PNGetChannelMetadataResponse is the Objects API Response for Get Space.
PNGetFileURLResponse is the File Upload API Response for Get Spaces.
PNGetMembershipsResponse is the Objects API Response for Get Memberships.
PNGetMessageActionsMore is the struct used when the PNGetMessageActionsResponse has more link.
PNGetMessageActionsResponse is the GetMessageActions API Response.
PNGetUUIDMetadataResponse is the Objects API Response for Get User.
PNGrantTokenData is the struct used to decode the server response.
PNGrantTokenDecoded is the struct used to decode the server response.
PNGrantTokenResponse is the struct returned when the Execute function of Grant Token is called.
PNHistoryMessageActionsTypeMap is the struct used in the Fetch request that includes Message Actions.
PNHistoryMessageActionTypeVal is the struct used in the Fetch request that includes Message Actions.
PNListFilesResponse is the File Upload API Response for Get Spaces.
PNManageChannelMembersBody is the Objects API input to add, remove or update members.
PNManageMembershipsBody is the Objects API input to add, remove or update membership.
PNManageMembershipsResponse is the Objects API Response for ManageMemberships.
PNManageMembersResponse is the Objects API Response for ManageMembers.
PNMembersAddChangeSet is the Objects API input to add, remove or update members.
PNMembershipEvent is the Response for a Membership Event.
PNMemberships is the Objects API Memberships struct.
PNMembershipsChannel is the Objects API Memberships input struct used to add members.
PNMembershipsRemove is the Objects API Memberships struct used to remove members.
PNMembershipsRemoveChangeSet is the Objects API input to add, remove or update members.
PNMembershipsSet is the Objects API Memberships input struct used to add members.
PNMessage is the Message Response for Subscribe.
PNMessageActionsEvent is the Response for a Message Actions Event.
PNMessageActionsResponse Message Actions response.
PNMPNSData is the struct used for the MPNS paylod.
PNObjectsResponse is the Objects API collective Response struct of all methods.
PNPAMEntityData is the struct containing the access details of the channels.
PNPresence is the Message Response for Presence.
PNPublishFileMessage is the message struct used in Publish File.
PNPublishMessage is the part of the message struct used in Publish File.
PNPushTarget is the helper struct used for the APNS2 paylod.
PNRemoveChannelMembersResponse is the Objects API Response for RemoveChannelMembers.
PNRemoveChannelMetadataResponse is the Objects API Response for delete space.
PNRemoveMembershipsResponse is the Objects API Response for RemoveMemberships.
PNRemoveMessageActionsResponse is the Objects API Response for create space.
PNRemoveUUIDMetadataResponse is the Objects API Response for delete user.
PNSendFileBody is used to create the body of the request.
PNSendFileResponse is the type used to store the response info of Send File.
PNSendFileResponseForS3 is the File Upload API Response for SendFile.
PNSendFileToS3Response is the File Upload API Response for Get Spaces.
PNSetChannelMembersResponse is the Objects API Response for SetChannelMembers.
PNSetChannelMetadataResponse is the Objects API Response for Update Space.
PNSetMembershipsResponse is the Objects API Response for SetMemberships.
PNSetUUIDMetadataResponse is the Objects API Response for Update user.
PNStatus is the status struct.
PNUUID is the Objects API user struct.
PNUUIDEvent is the Response for an User Event.
PublishFileMessageResponse is the response to PublishFileMessage request.
PublishResponse is the response after the execution on Publish and Fire operations.
PubNub No server connection will be established when you create a new PubNub object.
ReconnectionManager is used to store the properties required in running the Reconnection Manager.
RemoveAllPushChannelsForDeviceResponse is the struct returned when the Execute function of RemoveAllPushNotifications is called.
RemoveChannelFromChannelGroupResponse is the struct returned when the Execute function of RemoveChannelFromChannelGroup is called.
RemoveChannelsFromPushResponse is the struct returned when the Execute function of RemovePushNotificationsFromChannels is called.
RequestWorkers is the type to store the workers info.
ResourcePermissions contains all the applicable perms for bitmask translations.
ResponseInfo is used to store the properties in the response of an request.
SetChannelMetadataBody is the input to update space.
SetStateResponse is the response returned when the Execute function of SetState is called.
SetUUIDMetadataBody is the input to update user.
SignalResponse is the response to Signal request.
StateManager is used to store the subscriptions types.
StateOperation is the types to store state op params.
StatusResponse is used to store the usable properties in the response of an request.
SubscribeOperation is the type to store the subscribe op params.
SubscriptionItem is used to store the subscription item's properties.
SubscriptionManager Events: - ConnectedCategory - after connection established - DisconnectedCategory - after subscription loop stops for any reason (no channels left or error happened) Unsubscribe When you unsubscribe from channel or channel group the following events happens: - LoopStopCategory - immediately when no more channels or channel groups left to subscribe - PNUnsubscribeOperation - after leave request was fulfilled and server is notified about unsubscibed items Announcement: Status, Message and Presence announcement happens in a distinct goroutine.
TelemetryManager is the struct to store the Telemetry details.
TimeResponse is the response when Time call is executed.
TokenManager struct is used to for token manager operations.
UnsubscribeOperation is the types to store unsubscribe op params.
UserSpacePermissions contains all the acceptable perms for Users and Spaces.
UserSpacePermissionsWithToken is used for users/spaces resource type permissions.
WhereNowResponse is the response of the WhereNow request.
Worker is the type to store the worker info.

# Interfaces

Context interface.

# Type aliases

OperationType is used as an enum to catgorize the various operations in the APIs lifecycle.
PNChannelMembersInclude is used as an enum to catgorize the available Members include types.
PNChannelMetadataInclude is used as an enum to catgorize the available Channel include types.
PNGrantBitMask is the type for perms BitMask.
PNGrantType grant types.
PNMembershipsInclude is used as an enum to catgorize the available Memberships include types.
PNMessageActionsEventType is used as an enum to catgorize the available Message Actions Event types.
PNMessageType is used as an enum to catgorize the Subscribe response.
PNObjectsEvent is used as an enum to catgorize the available Object Events.
PNObjectsEventType is used as an enum to catgorize the available Object Event types.
PNPushEnvironment is used as an enum to catgorize the available Message Actions Event types.
PNPushType is used as an enum to catgorize the available Push Types.
PNResourceType grant types.
PNUUIDMetadataInclude is used as an enum to catgorize the available UUID include types.
ReconnectionPolicy is used as an enum to catgorize the reconnection policies.
StatusCategory is used as an enum to catgorize the various status events in the APIs lifecycle.