messaging

package
v3.7.1+incompatible Latest Latest
Warning

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

Go to latest
Published: Apr 8, 2016 License: MIT Imports: 23 Imported by: 0

README

Contact support@pubnub.com for all questions

#PubNub 3.7 client for Go 1.0.3, 1.1, 1.3, 1.3.1, 1.4.2, 1.5.2

###Important changes in this version:

  • The authKey argument was added to all PAM method.
  • Subscribe method arguments changed

###Change log

  • 3.7.0

  • Subscribe method arguments changed

  • Add authKey argument to all PAM methods

  • Add Channel Group Methods

  • Add PublishExtended() method that extends existing Publish() with 2 bool options: storeInHistory and doNotSerialize

  • Fix multiple channels encoding in PAM methods

  • 3.6.4

  • Exposed MaxIdleConnsPerHost of the transport

  • 3.6.3

  • PAM operations (grant, revoke, audit) now return 403 errors in the Error Callback

  • SetLogging method name changed to LoggingEnabled

  • SetLogOutput added, you can customize the log output now

  • Support to change uuid

  • 3.6 features

  • HereNow with state (here now's signature has changed, the response has also changed)

  • WhereNow

  • Global Here Now

  • User State (Set, Get, Delete)

  • Presence heartbeat

  • Presence heartbeat interval

  • These are converted to uint16

  • nonSubscribeTimeout

  • retryInterval

  • connectTimeout

  • subscribeTimeout

  • Optimizations

###Earlier Features

  • Supports multiplexing, UUID, SSL, Encryption, Proxy, and godoc
  • This version is not backward compatible. The major change is in the func calls. A new parameter "error callback" is added to the major functions of the pubnub class.
  • The client now supports:
  • Error Callback: All the error messages are routed to this callback channel
  • Resume on reconnect
  • You can now "Subscribe with timetoken"
  • An example of Disconnect/Retry has been added in the example
  • Multiple messages received in a single response from the server will now be split into individual messages
  • Non 200 response will now be bubbled to the client
  • PAM: To use the PAM features in the example please enable PAM from the Pubnub admin console (https://admin.pubnub.com) and replace the publish, subscribe and secret keys in example/pubnubExample.go (line 124).

###Quick Start Video

We've put together a quick HOWTO video here http://vimeo.com/93523019

###Get Package

  • Use the command go get github.com/pubnub/go/messaging to download and install the package

###Run the example

  • Built using Eclipse IDE (juno)
  • Install golang plugin for Eclipse
  • Using Eclipse Project Explorer browse to the directory $GOPATH/src/github.com/pubnub/go/messaging/example, where $GOPATH is the workspaces directory of go.
  • Run pubnubExample.go as a "go application"
  • Look for the application in the "Console" of the Eclipse IDE

###Running Unit tests (instructions for Mac/Linux, for other dev environments the instructions are similar)

  • Open Terminal.
  • Change the directory to <eclipse-workspace>/src/github.com/pubnub/go/messaging/tests.
  • Run the command go test -i to install the packages.
  • And then run the command go test to run test cases.

###Use pubnub in your project

  • Install golang plugin for Eclipse.
  • Use the command go get github.com/pubnub/go/messaging to download and install the package.
  • Open terminal/command prompt. Browse to the directory $GOPATH/src/github.com/pubnub/go/messaging/
  • Run the command go install.
  • Go to eclipse and create a new "go project". Enter the project name.
  • Create a new "go file" in the "src" directory of the new project. For this example choose the "Command Source File" under the "Source File Type" with "Empty Main Function".
  • Click Finish
  • On this file in eclipse.
  • Under import add the 2 lines
import (
    // Other imports...
    "fmt"
    "github.com/pubnub/go/messaging"
)
  • And under main add the following line
fmt.Println("PubNub Api for go;", messaging.VersionInfo())
  • Run the example as a "go application"
  • This application will print the version info of the PubNub Api.
  • For the detailed usage of the PunNub API, please refer to the rest of the ReadMe or the pubnubExample.go file under $GOPATH/src/github.com/pubnub/go/messaging/example

In addition to Eclipse, this has also been tested with Go 1.0.3 on Linux using IntelliJ IDEA 12.

###Demo Console App We've included a demo console app which documents all the functionality of the client, for example:

  • Subscribe
  • Subscribe with timetoken
  • Publish
  • PublishExtended
  • Presence
  • Detailed History
  • Here_Now
  • Unsubscribe
  • Presence-Unsubscribe
  • Time
  • Disconnect/Retry
  • GrantSubscribe
  • RevokeSubscribe
  • AuditSubscribe
  • GrantPresence
  • RevokePresence
  • AuditPresence
  • SetAuthKey
  • GetAuthKey
  • Exit
  • Set Presence Heartbeat
  • Set Presence Heartbeat Interval
  • Set User State by adding or modifying the Key-Pair
  • Delete an existing Key-Pair
  • Set User State with JSON string
  • Get User State
  • WhereNow
  • GlobalHereNow
  • Change UUID

###Quick Implementation Examples

handleSubscribeResult

This function is a utility function used in the examples below to handle the Subscribe/Presence response. You will want to adapt it to your own needs.

func handleSubscribeResult(successChannel, errorChannel chan []byte, action string) {
        for {
                select {
                case success, ok := <-successChannel:
                        if !ok {
                                break
                        }
                        if string(success) != "[]" {
                                fmt.Printf("%s Response: %s\n\n", action, success)
                        }
                case failure, ok := <-errorChannel:
                        if !ok {
                                break
                        }
                        if string(failure) != "[]" {
                                fmt.Printf("%s Error: %s\n\n", action, failure)
                        }
                case <-messaging.SubscribeTimeout():
                        fmt.Println("TODO: handle subscribe timeout")
                }
        }
}
handleResult

This function is a utility function used in the examples below to handle the non Subscribe/Presence response. You will want to adapt it to your own needs.

func handleResult(successChannel, errorChannel chan []byte, timeoutVal int64, action string) {
    timeout := make(chan bool, 1)
	go func() {
		time.Sleep(time.Duration(timeoutVal) * time.Second)
		timeout <- true
	}()
    for {
        select {
        case success, ok := <-successChannel:
            if !ok {
				break
			}
			if string(success) != "[]" {
				fmt.Println(fmt.Sprintf("%s Response: %s ", action, success))
				fmt.Println("")
			}
            return
        case failure, ok := <-errorChannel:
            if !ok {
				break
			}
            if string(failure) != "[]" {
				if displayError {
					fmt.Println(fmt.Sprintf("%s Error Callback: %s", action, failure))
					fmt.Println("")
				}
			}
            return
        case <-timeout:
            fmt.Println(fmt.Sprintf("%s Handler timeout after %d secs", action, timeoutVal))
			fmt.Println("")            
            return
        }
    }
}
Init

Initialize a new Pubnub instance.

        pubInstance := messaging.NewPubnub(<YOUR PUBLISH KEY>, <YOUR SUBSCRIBE KEY>, <SECRET KEY>, <CIPHER>, <SSL ON/OFF>, <UUID>)
Publish
        //Init pubnub instance

        var errorChannel = make(chan []byte)
        var callbackChannel = make(chan []byte)
        go pubInstance.Publish(<pubnub channel>, <message to publish>, callbackChannel, errorChannel)
        go handleResult(channel, errorChannel, messaging.GetNonSubscribeTimeout(), "Publish")
        // please goto the top of this file see the implementation of handleResult
PublishExtended
        //Init pubnub instance

        var errorChannel = make(chan []byte)
        var callbackChannel = make(chan []byte)
        go pubInstance.PublishExtended(<pubnub channel>, <message to publish>,
        	<storeInHistory bool>, <doNotSerialize bool>, callbackChannel, errorChannel)
        go handleResult(channel, errorChannel, messaging.GetNonSubscribeTimeout(), "PublishExtended")
        // please goto the top of this file see the implementation of handleResult
Subscribe
        //Init pubnub instance

        successChannel, errorChannel, eventsChannel := messaging.CreateSubscriptionChannels()
        go pubInstance.Subscribe(<pubnub channel, multiple channels can be separated by comma>,
        	successChannel, errorChannel, eventsChannel)
        go handleSubscribeResult(successChannel, errorChannel, eventsChannel)
        // please goto the top of this file see the implementation of handleSubscribeResult
Subscribe with timetoken
        //Init pubnub instance

        successChannel, errorChannel, eventsChannel := messaging.CreateSubscriptionChannels()
        go pubInstance.SubscribeWithTimetoken(<pubnub channel, multiple channels can be separated by comma>,
        	<timetoken to init the request with>, successChannel, errorChannel, eventsChannel)
        go handleSubscribeResult(successChannel, errorChannel, eventsChannel)
        // please goto the top of this file see the implementation of handleSubscribeResult
Presence
        //Init pubnub instance

        successChannel, errorChannel, eventsChannel := messaging.CreateSubscriptionChannels()
        go pubInstance.Subscribe(<pubnub channels, multiple channels can be separated by comma>,
        	successChannel, errorChannel, eventsChannel)
        go handleSubscribeResult(successChannel, errorChannel, eventsChannel)
        // please goto the top of this file see the implementation of handleSubscribeResult
Channel Group Subscribe
        //Init pubnub instance

        successChannel, errorChannel, eventsChannel := messaging.CreateSubscriptionChannels()
        go pubInstance.ChannelGroupSubscribe(
        	<pubnub channel group, multiple channel groupss can be separated by comma>,
        	successChannel, errorChannel, eventsChannel)
        go handleSubscribeResult(successChannel, errorChannel, eventsChannel)
        // please goto the top of this file see the implementation of handleSubscribeResult
Channel Group Subscribe with timetoken
        //Init pubnub instance

        successChannel, errorChannel, eventsChannel := messaging.CreateSubscriptionChannels()
        go pubInstance.ChannelGroupSubscribeWithTimetoken(
        	<pubnub channel group, multiple channel groupss can be separated by comma>,
        	<timetoken to init the request with>, successChannel, errorChannel, eventsChannel)
        go handleSubscribeResult(successChannel, errorChannel, eventsChannel)
        // please goto the top of this file see the implementation of handleSubscribeResult
Detailed History
        //Init pubnub instance

        var errorChannel = make(chan []byte)
        var channelCallback = make(chan []byte)
        go pubInstance.History(<pubnub channel>, <no of items to fetch>, <start time>, <end time>, false, channelCallback, errorChannel)
        //example: go _pub.History(<pubnub channel>, 100, 0, 0, false, channelCallback, errorChannel)
        go handleResult(channel, errorChannel, messaging.GetNonSubscribeTimeout(), "Detailed History") 
        // please goto the top of this file see the implementation of handleResult
Here_Now
        //Init pubnub instance

        var errorChannel = make(chan []byte)
        var channelCallback = make(chan []byte)
        go pubInstance.HereNow(<pubnub channel>, showUuid, includeUserState, channelCallback, errorChannel)
        go handleResult(channel, errorChannel, messaging.GetNonSubscribeTimeout(), "HereNow")
        // please goto the top of this file see the implementation of handleResult
Unsubscribe
        //Init pubnub instance

        var errorChannel = make(chan []byte)
        var channelCallback = make(chan []byte)
        go pubInstance.Unsubscribe(<pubnub channels, multiple channels can be separated by comma>, channelCallback, errorChannel)
        go handleResult(channel, errorChannel, messaging.GetNonSubscribeTimeout(), "Unsubscribe")
        // please goto the top of this file see the implementation of handleResult
Presence-Unsubscribe
        //Init pubnub instance

        var errorChannel = make(chan []byte)
        var channelCallback = make(chan []byte)
        go pubInstance.PresenceUnsubscribe(<pubnub channels, multiple channels can be separated by comma>, channelCallback, errorChannel)
        go handleResult(channel, errorChannel, messaging.GetNonSubscribeTimeout(), "UnsubscribePresence")
        // please goto the top of this file see the implementation of handleResult
Time
        //Init pubnub instance

        var errorChannel = make(chan []byte)
        var channelCallback = make(chan []byte)
        go pubInstance.GetTime(channelCallback, errorChannel)
        go handleResult(channel, errorChannel, messaging.GetNonSubscribeTimeout(), "Time")
        // please goto the top of this file see the implementation of handleResult
Disconnect/Retry
        //Init pubnub instance

        pubInstance.CloseExistingConnection() 
GrantSubscribe
        //Init pubnub instance

        var errorChannel = make(chan []byte)
        var pamChannel = make(chan []byte)
        go pub.GrantSubscribe(<pubnub channels>, true, true, 60, <auth keys>, pamChannel, errorChannel)
        go handleResult(pamChannel, errorChannel, messaging.GetNonSubscribeTimeout(), "Susbcribe Grant")
        // please goto the top of this file see the implementation of handleResult
RevokeSubscribe
        //Init pubnub instance

        var errorChannel = make(chan []byte)
        var pamChannel = make(chan []byte)
        go pub.GrantSubscribe(<pubnub channels>, false, false, -1, <auth keys>, pamChannel, errorChannel)
        go handleResult(pamChannel, errorChannel, messaging.GetNonSubscribeTimeout(), "Revoke Subscribe")
        // please goto the top of this file see the implementation of handleResult
AuditSubscribe
        //Init pubnub instance

        var errorChannel = make(chan []byte)
        var pamChannel = make(chan []byte)
        go pub.AuditSubscribe(<pubnub channels>, <auth keys>, pamChannel, errorChannel)
        go handleResult(pamChannel, errorChannel, messaging.GetNonSubscribeTimeout(), "Audit Subscribe")
        // please goto the top of this file see the implementation of handleResult
GrantPresence
        //Init pubnub instance

        var errorChannel = make(chan []byte)
        var pamChannel = make(chan []byte)
        go pub.GrantPresence(<pubnub channels>, true, true, 60, <auth keys>, pamChannel, errorChannel)
        go handleResult(pamChannel, errorChannel, messaging.GetNonSubscribeTimeout(), "Presence Grant")
        // please goto the top of this file see the implementation of handleResult
RevokePresence
        //Init pubnub instance

        var errorChannel = make(chan []byte)
        var pamChannel = make(chan []byte)
        go pub.GrantPresence(<pubnub channels>, false, false, -1, <auth keys>, pamChannel, errorChannel)
        go handleResult(pamChannel, errorChannel, messaging.GetNonSubscribeTimeout(), "Revoke presence")
        // please goto the top of this file see the implementation of handleResult
AuditPresence
        //Init pubnub instance

        var errorChannel = make(chan []byte)
        var pamChannel = make(chan []byte)
        go pub.AuditPresence(<pubnub channels>, <auth keys>, pamChannel, errorChannel)
        go handleResult(pamChannel, errorChannel, messaging.GetNonSubscribeTimeout(), "Audit Presence")
        // please goto the top of this file see the implementation of handleResult
GrantChannelGroup
        //Init pubnub instance

        var errorChannel = make(chan []byte)
        var pamChannel = make(chan []byte)
        go pub.GrantChannelGroup(<pubnub channel groups>, true, true, 60, <auth keys>, pamChannel, errorChannel)
        go handleResult(pamChannel, errorChannel, messaging.GetNonSubscribeTimeout(), "Channel Group Grant")
        // please goto the top of this file see the implementation of handleResult
RevokeChannelGroup
        //Init pubnub instance

        var errorChannel = make(chan []byte)
        var pamChannel = make(chan []byte)
        go pub.GrantChannelGroup(<pubnub channel groups>, false, false, -1, <auth keys>, pamChannel, errorChannel)
        go handleResult(pamChannel, errorChannel, messaging.GetNonSubscribeTimeout(), "Revoke Channel Group")
        // please goto the top of this file see the implementation of handleResult
AuditChannelGroup
        //Init pubnub instance

        var errorChannel = make(chan []byte)
        var pamChannel = make(chan []byte)
        go pub.AuditChannelGroup(<pubnub channel groups>, <auth keys>, pamChannel, errorChannel)
        go handleResult(pamChannel, errorChannel, messaging.GetNonSubscribeTimeout(), "Audit Channel Group")
        // please goto the top of this file see the implementation of handleResult
SetAuthKey
        //Init pubnub instance

        pub.SetAuthenticationKey("authkey")
GetAuthKey
        //Init pubnub instance

        fmt.Println(pub.GetAuthenticationKey())
Set Presence Heartbeat
        //Init pubnub instance

        pub.SetPresenceHeartbeat(<presenceHeartbeat>)
Set Presence Heartbeat Interval
        //Init pubnub instance

        pub.SetPresenceHeartbeatInterval(<presenceHeartbeatInterval>)
Set User State using Key-Pair
        //Init pubnub instance

        var errorChannel = make(chan []byte)
        var successChannel = make(chan []byte)
        go pub.SetUserStateKeyVal(<pubnub channel>, <key>, <val>, successChannel, errorChannel)
        go handleResult(successChannel, errorChannel, messaging.GetNonSubscribeTimeout(), "Set User State")
        // please goto the top of this file see the implementation of handleResult
Delete User State
        //Init pubnub instance

        var errorChannel = make(chan []byte)
        var successChannel = make(chan []byte)
        go pub.SetUserStateKeyVal(<pubnub channel>, <key>, "", successChannel, errorChannel)
        go handleResult(successChannel, errorChannel, messaging.GetNonSubscribeTimeout(), "Del User State")
        // please goto the top of this file see the implementation of handleResult
Set User State using JSON
        //Init pubnub instance

        var errorChannel = make(chan []byte)
        var successChannel = make(chan []byte)
        go pub.SetUserStateJSON(<pubnub channel>, <jsonString>, successChannel, errorChannel)
        go handleResult(successChannel, errorChannel, messaging.GetNonSubscribeTimeout(), "Set User State JSON")
        // please goto the top of this file see the implementation of handleResult
Get User State
        //Init pubnub instance

        var errorChannel = make(chan []byte)
        var successChannel = make(chan []byte)
        go pub.GetUserState(<pubnub channel>, successChannel, errorChannel)
        go handleResult(successChannel, errorChannel, messaging.GetNonSubscribeTimeout(), "Get User State")
        // please goto the top of this file see the implementation of handleResult
Where Now
        //Init pubnub instance

        var errorChannel = make(chan []byte)
        var successChannel = make(chan []byte)
        go pub.WhereNow(<uuid>, successChannel, errorChannel)
        go handleResult(successChannel, errorChannel, messaging.GetNonSubscribeTimeout(), "WhereNow")

	// please goto the top of this file see the implementation of handleResult
Global Here Now
        //Init pubnub instance

        var errorChannel = make(chan []byte)
        var successChannel = make(chan []byte)
        go pub.GlobalHereNow(showUuid, includeUserState, successChannel, errorChannel)
        go handleResult(successChannel, errorChannel, messaging.GetNonSubscribeTimeout(), "Global here now")

	// please goto the top of this file see the implementation of handleResult
Change UUID
        //Init pubnub instance

        pub.SetUUID(<uuid>)
Exit
        //Init pubnub instance

        pubInstance.Abort()  

Contact support@pubnub.com for all questions

Documentation

Overview

Package messaging provides the implemetation to connect to pubnub api. Version: 3.7.1 Build Date: Apr 8, 2016

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DecryptString

func DecryptString(cipherKey string, message string) (retVal interface{}, err error)

DecryptString decodes encrypted string using the cipherKey

It accepts the following parameters: cipherKey: cipher key to use to decrypt. message: to encrypted.

returns the unencoded encrypted string, error if any.

func EncryptString

func EncryptString(cipherKey string, message string) string

EncryptString creates the base64 encoded encrypted string using the cipherKey. It accepts the following parameters: cipherKey: cipher key to use to encrypt. message: to encrypted.

returns the base64 encoded encrypted string.

func GenUuid

func GenUuid() (string, error)

GenUuid generates a unique UUID returns the unique UUID or error.

func GetNonSubscribeTimeout

func GetNonSubscribeTimeout() uint16

GetNonSubscribeTimeout gets the value of nonSubscribeTimeout

func GetResumeOnReconnect

func GetResumeOnReconnect() bool

GetResumeOnReconnect returns the value of resumeOnReconnect.

func GetSubscribeTimeout

func GetSubscribeTimeout() uint16

GetSubscribeTimeout gets the value of subscribeTimeout

func Logging

func Logging() bool

Logging gets the value of loggingEnabled If true logs will be written to a file

func LoggingEnabled

func LoggingEnabled(val bool)

LoggingEnabled sets the value of loggingEnabled If true logs will be written to the logfileWriter In addition to LoggingEnabled you also need to init the logfileWriter using SetLogOutput

func ParseInterfaceData

func ParseInterfaceData(myInterface interface{}) string

ParseInterfaceData formats the data to string as per the type of the data.

It accepts the following parameters: myInterface: the interface data to parse and convert to string.

returns: the data in string format.

func ParseJSON

func ParseJSON(contents []byte,
	cipherKey string) (string, string, string, error)

ParseJSON parses the json data. It extracts the actual data (value 0), Timetoken/from time in case of detailed history (value 1), pubnub channelname/timetoken/to time in case of detailed history (value 2).

It accepts the following parameters: contents: the contents to parse. cipherKey: the key to decrypt the messages (can be empty).

returns: data: as string. Timetoken/from time in case of detailed history as string. pubnub channelname/timetoken/to time in case of detailed history (value 2). error if any.

func ParseSubscribeResponse

func ParseSubscribeResponse(rawResponse []byte, cipherKey string) (
	messages [][]byte, channels, groups []string, timetoken string, err error)

ParseSubscribeResponse It extracts the actual data (value 0), Timetoken/from time in case of detailed history (value 1), pubnub channelname/timetoken/to time in case of detailed history (value 2).

It accepts the following parameters: contents: the contents to parse. cipherKey: the key to decrypt the messages (can be empty).

returns: messages: as [][]byte. channels: as string. groups: as string. Timetoken/from time in case of detailed history as string. error: if any.

func SetConnectTimeout

func SetConnectTimeout(val uint16)

SetConnectTimeout sets the value of connectTimeout.

func SetIV

func SetIV(val string)

SetIV sets the value of valIV.

func SetLogOutput

func SetLogOutput(val io.Writer)

SetLogOutput sets the full path of the logfile Default name is pubnubMessaging.log and is located in the same dir from where the go file is run In addition to this LoggingEnabled should be true for this to work.

func SetMaxIdleConnsPerHost

func SetMaxIdleConnsPerHost(maxIdleConnsPerHostVal int)

SetMaxIdleConnsPerHost is used to set the value of HTTP Transport's MaxIdleConnsPerHost. It restricts how many connections there are which are not actively serving requests, but which the client has not closed. Be careful when increasing MaxIdleConnsPerHost to a large number. It only makes sense to increase idle connections if you are seeing many connections in a short period from the same clients.

func SetMaxRetries

func SetMaxRetries(val int)

SetMaxRetries sets the value of maxRetries.

func SetNonSubscribeTimeout

func SetNonSubscribeTimeout(val uint16)

SetNonSubscribeTimeout sets the value of nonsubscribeTimeout.

func SetNonSubscribeTransport

func SetNonSubscribeTransport(transport http.RoundTripper)

func SetOrigin

func SetOrigin(val string)

SetOrigin sets the value of _origin. Should be called before PubnubInit

func SetProxy

func SetProxy(proxyServerVal string, proxyPortVal int, proxyUserVal string, proxyPasswordVal string)

SetProxy sets the global variables for the parameters. It also sets the proxyServerEnabled value to true.

It accepts the following parameters: proxyServer proxy server name or ip. proxyPort proxy port. proxyUser proxyUserName. proxyPassword proxyPassword.

func SetResumeOnReconnect

func SetResumeOnReconnect(val bool)

SetResumeOnReconnect sets the value of resumeOnReconnect.

func SetRetryInterval

func SetRetryInterval(val uint16)

SetRetryInterval sets the value of retryInterval.

func SetSubscribeConn

func SetSubscribeConn(conn net.Conn)

func SetSubscribeTimeout

func SetSubscribeTimeout(val uint16)

SetSubscribeTimeout sets the value of subscribeTimeout.

func SetSubscribeTransport

func SetSubscribeTransport(transport http.RoundTripper)

func SubscribeTimeout

func SubscribeTimeout() <-chan time.Time

Timeout channel for subscribe requests

func Timeout

func Timeout() <-chan time.Time

Timeout channel for non-subscribe requests

func Timeouts

func Timeouts(seconds uint16) <-chan time.Time

Timeout channel with custon timeout value

func VersionInfo

func VersionInfo() string

VersionInfo returns the version of the this code along with the build date.

Types

type PresenceEvent

type PresenceEvent struct {
	Action    string  `json:"action"`
	Uuid      string  `json:"uuid"`
	Timestamp float64 `json:"timestamp"`
	Occupancy int     `json:"occupancy"`
}

Type for presence events

type PresenceResonse

type PresenceResonse struct {
	Action  string `json:"action"`
	Status  int    `json:"status"`
	Service string `json:"service"`
	Message string `json:"message"`
}

Type for presence response

type Pubnub

type Pubnub struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

Pubnub structure. origin stores the root url value of pubnub api in the current instance. publishKey stores the user specific Publish Key in the current instance. subscribeKey stores the user specific Subscribe Key in the current instance. secretKey stores the user specific Secret Key in the current instance. cipherKey stores the user specific Cipher Key in the current instance. authenticationKey stores the Authentication Key in the current instance. isSSL is true if enabled, else is false for the current instance. uuid is the unique identifier, it can be a custom value or is automatically generated. timeToken is the current value of the servertime. This will be used to appened in each request. sentTimeToken: This is the timetoken sent to the server with the request resetTimeToken: In case of a new request or an error this variable is set to true so that the

timeToken will be set to 0 in the next request.

channels: container for channels groups: container for channels groups isPresenceHeartbeatRunning a variable to keep a check on the presence heartbeat's status Mutex to lock the operations on the instance

func NewPubnub

func NewPubnub(publishKey string, subscribeKey string, secretKey string, cipherKey string, sslOn bool, customUuid string) *Pubnub

NewPubnub initializes pubnub struct with the user provided values. And then initiates the origin by appending the protocol based upon the sslOn argument. Then it uses the customuuid or generates the uuid.

It accepts the following parameters: publishKey is the user specific Publish Key. Mandatory. subscribeKey is the user specific Subscribe Key. Mandatory. secretKey is the user specific Secret Key. Accepts empty string if not used. cipherKey stores the user specific Cipher Key. Accepts empty string if not used. sslOn is true if enabled, else is false. customUuid is the unique identifier, it can be a custom value or sent as empty for automatic generation.

returns the pointer to Pubnub instance.

func (*Pubnub) Abort

func (pub *Pubnub) Abort()

Abort is the struct Pubnub's instance method that closes the open connections for both subscribe and non-subscribe requests.

It also sends a leave request for all the subscribed channel and resets both channel and group collections to break the loop in the func StartSubscribeLoop

func (*Pubnub) AuditChannelGroup

func (pub *Pubnub) AuditChannelGroup(group, authKey string,
	callbackChannel, errorChannel chan []byte)

AuditChannelGroup will make a call to display the permissions for a channel group or subkey

func (*Pubnub) AuditPresence

func (pub *Pubnub) AuditPresence(channel, authKey string,
	callbackChannel, errorChannel chan []byte)

AuditPresence will make a call to display the permissions for a channel or subkey

channel is options and if not provided will set the permissions at subkey level

Both callbackChannel and errorChannel are mandatory. If either is nil the code will panic

func (*Pubnub) AuditSubscribe

func (pub *Pubnub) AuditSubscribe(channel, authKey string,
	callbackChannel, errorChannel chan []byte)

AuditSubscribe will make a call to display the permissions for a channel or subkey

channel is options and if not provided will set the permissions at subkey level

Both callbackChannel and errorChannel are mandatory. If either is nil the code will panic

func (*Pubnub) ChannelGroupAddChannel

func (pub *Pubnub) ChannelGroupAddChannel(group, channel string,
	callbackChannel, errorChannel chan []byte)

func (*Pubnub) ChannelGroupListChannels

func (pub *Pubnub) ChannelGroupListChannels(group string,
	callbackChannel, errorChannel chan []byte)

func (*Pubnub) ChannelGroupRemoveChannel

func (pub *Pubnub) ChannelGroupRemoveChannel(group, channel string,
	callbackChannel, errorChannel chan []byte)

func (*Pubnub) ChannelGroupRemoveGroup

func (pub *Pubnub) ChannelGroupRemoveGroup(group string,
	callbackChannel, errorChannel chan []byte)

func (*Pubnub) ChannelGroupSubscribe

func (pub *Pubnub) ChannelGroupSubscribe(groups string,
	callbackChannel chan<- []byte, errorChannel chan<- []byte)

func (*Pubnub) ChannelGroupSubscribeWithTimetoken

func (pub *Pubnub) ChannelGroupSubscribeWithTimetoken(groups, timetoken string,
	callbackChannel chan<- []byte, errorChannel chan<- []byte)

func (*Pubnub) ChannelGroupUnsubscribe

func (pub *Pubnub) ChannelGroupUnsubscribe(groups string, callbackChannel,
	errorChannel chan []byte)

func (*Pubnub) CloseExistingConnection

func (pub *Pubnub) CloseExistingConnection()

CloseExistingConnection closes the open subscribe/presence connection.

func (*Pubnub) GetAuthenticationKey

func (pub *Pubnub) GetAuthenticationKey() string

GetAuthenticationKey gets the value of authentication key

func (*Pubnub) GetPresenceHeartbeat

func (pub *Pubnub) GetPresenceHeartbeat() uint16

GetPresenceHeartbeat gets the value of presenceHeartbeat

func (*Pubnub) GetPresenceHeartbeatInterval

func (pub *Pubnub) GetPresenceHeartbeatInterval() uint16

GetPresenceHeartbeatInterval gets the value of presenceHeartbeatInterval

func (*Pubnub) GetTime

func (pub *Pubnub) GetTime(callbackChannel chan []byte, errorChannel chan []byte)

GetTime is the struct Pubnub's instance method that calls the ExecuteTime method to process the time request. . It accepts the following parameters: callbackChannel on which to send the response. errorChannel on which to send the error response.

Both callbackChannel and errorChannel are mandatory. If either is nil the code will panic

func (*Pubnub) GetUUID

func (pub *Pubnub) GetUUID() string

GetUUID returns the value of UUID

func (*Pubnub) GetUserState

func (pub *Pubnub) GetUserState(channel string, callbackChannel chan []byte, errorChannel chan []byte)

GetUserState is the struct Pubnub's instance method which creates and posts the GetUserState request to get the connected users details.

It accepts the following parameters: channel: a single value of the pubnub channel. callbackChannel on which to send the response. errorChannel on which the error response is sent.

Both callbackChannel and errorChannel are mandatory. If either is nil the code will panic

func (*Pubnub) GlobalHereNow

func (pub *Pubnub) GlobalHereNow(showUuid bool, includeUserState bool, callbackChannel chan []byte, errorChannel chan []byte)

GlobalHereNow is the struct Pubnub's instance method which creates and posts the globalherenow request to get the connected users details.

It accepts the following parameters: showUuid: if true uuids of devices will be fetched in the respose includeUserState: if true the user states of devices will be fetched in the respose callbackChannel on which to send the response. errorChannel on which the error response is sent.

Both callbackChannel and errorChannel are mandatory. If either is nil the code will panic

func (*Pubnub) GrantChannelGroup

func (pub *Pubnub) GrantChannelGroup(group string, read, manage bool,
	ttl int, authKey string, callbackChannel, errorChannel chan []byte)

GrantChannelGroup is used to give a channel group read or manage permissions and set TTL values for it.

ttl values:

-1: do not include ttl param to query, use default (60 minutes)
 0: permissions will never expire
1..525600: from 1 minute to 1 year(in minutes)

func (*Pubnub) GrantPresence

func (pub *Pubnub) GrantPresence(channel string, read, write bool, ttl int,
	authKey string, callbackChannel, errorChannel chan []byte)

GrantPresence is used to give a presence channel read, write permissions and set TTL values for it. To grant a permission set read or write as true to revoke all perms set read and write false and ttl as -1

ttl values:

-1: do not include ttl param to query, use default (60 minutes)
 0: permissions will never expire
1..525600: from 1 minute to 1 year(in minutes)

channel is options and if not provided will set the permissions at subkey level

Both callbackChannel and errorChannel are mandatory. If either is nil the code will panic

func (*Pubnub) GrantSubscribe

func (pub *Pubnub) GrantSubscribe(channel string, read, write bool,
	ttl int, authKey string, callbackChannel, errorChannel chan []byte)

GrantSubscribe is used to give a subscribe channel read, write permissions and set TTL values for it. To grant a permission set read or write as true to revoke all perms set read and write false and ttl as -1

ttl values:

-1: do not include ttl param to query, use default (60 minutes)
 0: permissions will never expire
1..525600: from 1 minute to 1 year(in minutes)

channel is options and if not provided will set the permissions at subkey level

Both callbackChannel and errorChannel are mandatory. If either is nil the code will panic

func (*Pubnub) HereNow

func (pub *Pubnub) HereNow(channel string, showUuid bool, includeUserState bool, callbackChannel chan []byte, errorChannel chan []byte)

HereNow is the struct Pubnub's instance method which creates and posts the herenow request to get the connected users details.

It accepts the following parameters: channel: a single value of the pubnub channel. callbackChannel on which to send the response. errorChannel on which the error response is sent.

Both callbackChannel and errorChannel are mandatory. If either is nil the code will panic

func (*Pubnub) History

func (pub *Pubnub) History(channel string, limit int, start int64, end int64, reverse bool, callbackChannel chan []byte, errorChannel chan []byte)

History is the struct Pubnub's instance method which creates and post the History request for a single pubnub channel.

It parses the response to get the data and return it to the channel.

It accepts the following parameters: channel: a single value of the pubnub channel. limit: number of history messages to return. start: start time from where to begin the history messages. end: end time till where to get the history messages. reverse: to fetch the messages in ascending order callbackChannel on which to send the response. errorChannel on which the error response is sent.

Both callbackChannel and errorChannel are mandatory. If either is nil the code will panic

func (*Pubnub) PresenceUnsubscribe

func (pub *Pubnub) PresenceUnsubscribe(channels string, callbackChannel,
	errorChannel chan []byte)

PresenceUnsubscribe is the struct Pubnub's instance method which unsubscribes a pubnub presence channel(s) from the subscribe loop.

If all the pubnub channels are not removed the method StartSubscribeLoop will take care of it by starting a new loop. When the pubnub channel(s) are removed it creates and posts a leave request.

It accepts the following parameters: channels: the pubnub channel(s) in a comma separated string. callbackChannel: Channel on which to send the response back. errorChannel: channel to send an error response to.

Both callbackChannel and errorChannel are mandatory. If either is nil the code will panic

func (*Pubnub) Publish

func (pub *Pubnub) Publish(channel string, message interface{},
	callbackChannel, errorChannel chan []byte)

Publish is the struct Pubnub's instance method that creates a publish request and calls SendPublishRequest to post the request.

It calls the InvalidChannel and InvalidMessage methods to validate the Pubnub channels and message. Calls the GetHmacSha256 to generate a signature if a secretKey is to be used. Creates the publish url Calls json marshal Calls the EncryptString method is the cipherkey is used and calls json marshal Closes the channel after the response is received

It accepts the following parameters: channel: The Pubnub channel to which the message is to be posted. message: message to be posted. callbackChannel: Channel on which to send the response back. errorChannel on which the error response is sent.

Both callbackChannel and errorChannel are mandatory. If either is nil the code will panic

func (*Pubnub) PublishExtended

func (pub *Pubnub) PublishExtended(channel string, message interface{},
	storeInHistory, doNotSerialize bool,
	callbackChannel, errorChannel chan []byte)

Publish is the struct Pubnub's instance method that creates a publish request and calls SendPublishRequest to post the request.

It calls the InvalidChannel and InvalidMessage methods to validate the Pubnub channels and message. Calls the GetHmacSha256 to generate a signature if a secretKey is to be used. Creates the publish url Calls json marshal Calls the EncryptString method is the cipherkey is used and calls json marshal Closes the channel after the response is received

It accepts the following parameters: channel: The Pubnub channel to which the message is to be posted. message: message to be posted. storeInHistory: Message will be persisted in Storage & Playback db doNotSerialize: Set this option to true if you use your own serializer. In this case passed-in message should be a string or []byte callbackChannel: Channel on which to send the response back. errorChannel on which the error response is sent.

Both callbackChannel and errorChannel are mandatory. If either is nil the code will panic

func (*Pubnub) SetAuthenticationKey

func (pub *Pubnub) SetAuthenticationKey(val string)

SetAuthenticationKey sets the value of authentication key

func (*Pubnub) SetPresenceHeartbeat

func (pub *Pubnub) SetPresenceHeartbeat(val uint16)

SetPresenceHeartbeat sets the value of presence heartbeat. When the presence heartbeat is set the presenceHeartbeatInterval is automatically set to (presenceHeartbeat / 2) - 1 Starts the presence heartbeat request if both presenceHeartbeatInterval and presenceHeartbeat are set and a presence notifications are subsribed

func (*Pubnub) SetPresenceHeartbeatInterval

func (pub *Pubnub) SetPresenceHeartbeatInterval(val uint16)

SetPresenceHeartbeatInterval sets the value of presenceHeartbeatInterval. If the value is greater than presenceHeartbeat and there is a value set for presenceHeartbeat then is automatically set to (presenceHeartbeat / 2) - 1 Starts the presence heartbeat request if both presenceHeartbeatInterval and presenceHeartbeat are set and a presence notifications are subsribed

func (*Pubnub) SetUUID

func (pub *Pubnub) SetUUID(val string)

SetUUID sets the value of UUID

func (*Pubnub) SetUserStateJSON

func (pub *Pubnub) SetUserStateJSON(channel string, jsonString string, callbackChannel chan []byte, errorChannel chan []byte)

SetUserStateJSON is the struct Pubnub's instance method which creates and posts the User state request using JSON as input

It accepts the following parameters: channel: a single value of the pubnub channel. jsonString: the user state in JSON format. If invalid an error will be thrown callbackChannel on which to send the response. errorChannel on which the error response is sent.

Both callbackChannel and errorChannel are mandatory. If either is nil the code will panic

func (*Pubnub) SetUserStateKeyVal

func (pub *Pubnub) SetUserStateKeyVal(channel string, key string, val string, callbackChannel chan []byte, errorChannel chan []byte)

SetUserStateKeyVal is the struct Pubnub's instance method which creates and posts the userstate request using a key/val map

It accepts the following parameters: channel: a single value of the pubnub channel. key: user states key value: user stated value callbackChannel on which to send the response. errorChannel on which the error response is sent.

Both callbackChannel and errorChannel are mandatory. If either is nil the code will panic

func (*Pubnub) Subscribe

func (pub *Pubnub) Subscribe(channels, timetoken string,
	callbackChannel chan<- []byte, isPresence bool, errorChannel chan<- []byte)

Subscribe is the struct Pubnub's instance method which checks for the InvalidChannels and returns if true. Initaiates the presence and subscribe response channels.

If there is no existing subscribe/presence loop running then it starts a new loop with the new pubnub channels. Else closes the existing connections and starts a new loop

It accepts the following parameters: channels: comma separated pubnub channel list. timetoken: if timetoken is present the subscribe request is sent using this timetoken successChannel: Channel on which to send the success response back. errorChannel: channel to send an error response to. eventsChannel: Channel on which to send events like connect/disconnect/reconnect.

func (*Pubnub) Unsubscribe

func (pub *Pubnub) Unsubscribe(channels string, callbackChannel, errorChannel chan []byte)

Unsubscribe is the struct Pubnub's instance method which unsubscribes a pubnub subscribe channel(s) from the subscribe loop.

If all the pubnub channels are not removed the method StartSubscribeLoop will take care of it by starting a new loop. Closes the channel c when the processing is complete

It accepts the following parameters: channels: the pubnub channel(s) in a comma separated string. callbackChannel: Channel on which to send the response back. errorChannel: channel to send an error response to.

Both callbackChannel and errorChannel are mandatory. If either is nil the code will panic

func (*Pubnub) WhereNow

func (pub *Pubnub) WhereNow(uuid string, callbackChannel chan []byte, errorChannel chan []byte)

WhereNow is the struct Pubnub's instance method which creates and posts the wherenow request to get the connected users details.

It accepts the following parameters: uuid: devcie uuid to pass to the wherenow query callbackChannel on which to send the response. errorChannel on which the error response is sent.

Both callbackChannel and errorChannel are mandatory. If either is nil the code will panic

type PubnubUnitTest

type PubnubUnitTest struct {
}

PubnubUnitTest structure used to expose some data for unit tests.

func (*PubnubUnitTest) GetSentTimeToken

func (pubtest *PubnubUnitTest) GetSentTimeToken(pub *Pubnub) string

GetSentTimeToken returns the timetoken sent to the server, is used only for unit tests

func (*PubnubUnitTest) GetTimeToken

func (pubtest *PubnubUnitTest) GetTimeToken(pub *Pubnub) string

GetTimeToken returns the latest timetoken received from the server, is used only for unit tests

Directories

Path Synopsis
examples
cli
Package main provides the example implemetation to connect to pubnub api.
Package main provides the example implemetation to connect to pubnub api.
Package tests has the unit tests of package messaging.
Package tests has the unit tests of package messaging.

Jump to

Keyboard shortcuts

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