repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
packets/pubcomp.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/packets/pubcomp.go#L43-L45
go
train
//Details returns a Details struct containing the Qos and //MessageID of this ControlPacket
func (pc *PubcompPacket) Details() Details
//Details returns a Details struct containing the Qos and //MessageID of this ControlPacket func (pc *PubcompPacket) Details() Details
{ return Details{Qos: pc.Qos, MessageID: pc.MessageID} }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
packets/packets.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/packets/packets.go#L101-L131
go
train
//ReadPacket takes an instance of an io.Reader (such as net.Conn) and attempts //to read an MQTT packet from the stream. It returns a ControlPacket //representing the decoded MQTT packet and an error. One of these returns will //always be nil, a nil ControlPacket indicating an error occurred.
func ReadPacket(r io.Reader) (ControlPacket, error)
//ReadPacket takes an instance of an io.Reader (such as net.Conn) and attempts //to read an MQTT packet from the stream. It returns a ControlPacket //representing the decoded MQTT packet and an error. One of these returns will //always be nil, a nil ControlPacket indicating an error occurred. func ReadPacket(r io.Reader) (ControlPacket, error)
{ var fh FixedHeader b := make([]byte, 1) _, err := io.ReadFull(r, b) if err != nil { return nil, err } err = fh.unpack(b[0], r) if err != nil { return nil, err } cp, err := NewControlPacketWithHeader(fh) if err != nil { return nil, err } packetBytes := make([]byte, fh.RemainingLength) n, err := io.ReadFull(r, packetBytes) if err != nil { return nil, err } if n != fh.RemainingLength { return nil, errors.New("Failed to read expected data") } err = cp.Unpack(bytes.NewBuffer(packetBytes)) return cp, err }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
packets/packets.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/packets/packets.go#L174-L206
go
train
//NewControlPacketWithHeader is used to create a new ControlPacket of the type //specified within the FixedHeader that is passed to the function. //The newly created ControlPacket is empty and a pointer is returned.
func NewControlPacketWithHeader(fh FixedHeader) (ControlPacket, error)
//NewControlPacketWithHeader is used to create a new ControlPacket of the type //specified within the FixedHeader that is passed to the function. //The newly created ControlPacket is empty and a pointer is returned. func NewControlPacketWithHeader(fh FixedHeader) (ControlPacket, error)
{ switch fh.MessageType { case Connect: return &ConnectPacket{FixedHeader: fh}, nil case Connack: return &ConnackPacket{FixedHeader: fh}, nil case Disconnect: return &DisconnectPacket{FixedHeader: fh}, nil case Publish: return &PublishPacket{FixedHeader: fh}, nil case Puback: return &PubackPacket{FixedHeader: fh}, nil case Pubrec: return &PubrecPacket{FixedHeader: fh}, nil case Pubrel: return &PubrelPacket{FixedHeader: fh}, nil case Pubcomp: return &PubcompPacket{FixedHeader: fh}, nil case Subscribe: return &SubscribePacket{FixedHeader: fh}, nil case Suback: return &SubackPacket{FixedHeader: fh}, nil case Unsubscribe: return &UnsubscribePacket{FixedHeader: fh}, nil case Unsuback: return &UnsubackPacket{FixedHeader: fh}, nil case Pingreq: return &PingreqPacket{FixedHeader: fh}, nil case Pingresp: return &PingrespPacket{FixedHeader: fh}, nil } return nil, fmt.Errorf("unsupported packet type 0x%x", fh.MessageType) }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
options.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L88-L117
go
train
// NewClientOptions will create a new ClientClientOptions type with some // default values. // Port: 1883 // CleanSession: True // Order: True // KeepAlive: 30 (seconds) // ConnectTimeout: 30 (seconds) // MaxReconnectInterval 10 (minutes) // AutoReconnect: True
func NewClientOptions() *ClientOptions
// NewClientOptions will create a new ClientClientOptions type with some // default values. // Port: 1883 // CleanSession: True // Order: True // KeepAlive: 30 (seconds) // ConnectTimeout: 30 (seconds) // MaxReconnectInterval 10 (minutes) // AutoReconnect: True func NewClientOptions() *ClientOptions
{ o := &ClientOptions{ Servers: nil, ClientID: "", Username: "", Password: "", CleanSession: true, Order: true, WillEnabled: false, WillTopic: "", WillPayload: nil, WillQos: 0, WillRetained: false, ProtocolVersion: 0, protocolVersionExplicit: false, KeepAlive: 30, PingTimeout: 10 * time.Second, ConnectTimeout: 30 * time.Second, MaxReconnectInterval: 10 * time.Minute, AutoReconnect: true, Store: nil, OnConnect: nil, OnConnectionLost: DefaultConnectionLostHandler, WriteTimeout: 0, // 0 represents timeout disabled MessageChannelDepth: 100, ResumeSubs: false, HTTPHeaders: make(map[string][]string), } return o }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
options.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L127-L141
go
train
// AddBroker adds a broker URI to the list of brokers to be used. The format should be // scheme://host:port // Where "scheme" is one of "tcp", "ssl", or "ws", "host" is the ip-address (or hostname) // and "port" is the port on which the broker is accepting connections. // // Default values for hostname is "127.0.0.1", for schema is "tcp://". // // An example broker URI would look like: tcp://foobar.com:1883
func (o *ClientOptions) AddBroker(server string) *ClientOptions
// AddBroker adds a broker URI to the list of brokers to be used. The format should be // scheme://host:port // Where "scheme" is one of "tcp", "ssl", or "ws", "host" is the ip-address (or hostname) // and "port" is the port on which the broker is accepting connections. // // Default values for hostname is "127.0.0.1", for schema is "tcp://". // // An example broker URI would look like: tcp://foobar.com:1883 func (o *ClientOptions) AddBroker(server string) *ClientOptions
{ if len(server) > 0 && server[0] == ':' { server = "127.0.0.1" + server } if !strings.Contains(server, "://") { server = "tcp://" + server } brokerURI, err := url.Parse(server) if err != nil { ERROR.Println(CLI, "Failed to parse %q broker address: %s", server, err) return o } o.Servers = append(o.Servers, brokerURI) return o }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
options.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L145-L148
go
train
// SetResumeSubs will enable resuming of stored (un)subscribe messages when connecting // but not reconnecting if CleanSession is false. Otherwise these messages are discarded.
func (o *ClientOptions) SetResumeSubs(resume bool) *ClientOptions
// SetResumeSubs will enable resuming of stored (un)subscribe messages when connecting // but not reconnecting if CleanSession is false. Otherwise these messages are discarded. func (o *ClientOptions) SetResumeSubs(resume bool) *ClientOptions
{ o.ResumeSubs = resume return o }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
options.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L153-L156
go
train
// SetClientID will set the client id to be used by this client when // connecting to the MQTT broker. According to the MQTT v3.1 specification, // a client id mus be no longer than 23 characters.
func (o *ClientOptions) SetClientID(id string) *ClientOptions
// SetClientID will set the client id to be used by this client when // connecting to the MQTT broker. According to the MQTT v3.1 specification, // a client id mus be no longer than 23 characters. func (o *ClientOptions) SetClientID(id string) *ClientOptions
{ o.ClientID = id return o }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
options.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L161-L164
go
train
// SetUsername will set the username to be used by this client when connecting // to the MQTT broker. Note: without the use of SSL/TLS, this information will // be sent in plaintext accross the wire.
func (o *ClientOptions) SetUsername(u string) *ClientOptions
// SetUsername will set the username to be used by this client when connecting // to the MQTT broker. Note: without the use of SSL/TLS, this information will // be sent in plaintext accross the wire. func (o *ClientOptions) SetUsername(u string) *ClientOptions
{ o.Username = u return o }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
options.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L169-L172
go
train
// SetPassword will set the password to be used by this client when connecting // to the MQTT broker. Note: without the use of SSL/TLS, this information will // be sent in plaintext accross the wire.
func (o *ClientOptions) SetPassword(p string) *ClientOptions
// SetPassword will set the password to be used by this client when connecting // to the MQTT broker. Note: without the use of SSL/TLS, this information will // be sent in plaintext accross the wire. func (o *ClientOptions) SetPassword(p string) *ClientOptions
{ o.Password = p return o }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
options.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L178-L181
go
train
// SetCredentialsProvider will set a method to be called by this client when // connecting to the MQTT broker that provide the current username and password. // Note: without the use of SSL/TLS, this information will be sent // in plaintext accross the wire.
func (o *ClientOptions) SetCredentialsProvider(p CredentialsProvider) *ClientOptions
// SetCredentialsProvider will set a method to be called by this client when // connecting to the MQTT broker that provide the current username and password. // Note: without the use of SSL/TLS, this information will be sent // in plaintext accross the wire. func (o *ClientOptions) SetCredentialsProvider(p CredentialsProvider) *ClientOptions
{ o.CredentialsProvider = p return o }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
options.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L189-L192
go
train
// SetCleanSession will set the "clean session" flag in the connect message // when this client connects to an MQTT broker. By setting this flag, you are // indicating that no messages saved by the broker for this client should be // delivered. Any messages that were going to be sent by this client before // diconnecting previously but didn't will not be sent upon connecting to the // broker.
func (o *ClientOptions) SetCleanSession(clean bool) *ClientOptions
// SetCleanSession will set the "clean session" flag in the connect message // when this client connects to an MQTT broker. By setting this flag, you are // indicating that no messages saved by the broker for this client should be // delivered. Any messages that were going to be sent by this client before // diconnecting previously but didn't will not be sent upon connecting to the // broker. func (o *ClientOptions) SetCleanSession(clean bool) *ClientOptions
{ o.CleanSession = clean return o }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
options.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L198-L201
go
train
// SetOrderMatters will set the message routing to guarantee order within // each QoS level. By default, this value is true. If set to false, // this flag indicates that messages can be delivered asynchronously // from the client to the application and possibly arrive out of order.
func (o *ClientOptions) SetOrderMatters(order bool) *ClientOptions
// SetOrderMatters will set the message routing to guarantee order within // each QoS level. By default, this value is true. If set to false, // this flag indicates that messages can be delivered asynchronously // from the client to the application and possibly arrive out of order. func (o *ClientOptions) SetOrderMatters(order bool) *ClientOptions
{ o.Order = order return o }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
options.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L206-L209
go
train
// SetTLSConfig will set an SSL/TLS configuration to be used when connecting // to an MQTT broker. Please read the official Go documentation for more // information.
func (o *ClientOptions) SetTLSConfig(t *tls.Config) *ClientOptions
// SetTLSConfig will set an SSL/TLS configuration to be used when connecting // to an MQTT broker. Please read the official Go documentation for more // information. func (o *ClientOptions) SetTLSConfig(t *tls.Config) *ClientOptions
{ o.TLSConfig = t return o }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
options.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L215-L218
go
train
// SetStore will set the implementation of the Store interface // used to provide message persistence in cases where QoS levels // QoS_ONE or QoS_TWO are used. If no store is provided, then the // client will use MemoryStore by default.
func (o *ClientOptions) SetStore(s Store) *ClientOptions
// SetStore will set the implementation of the Store interface // used to provide message persistence in cases where QoS levels // QoS_ONE or QoS_TWO are used. If no store is provided, then the // client will use MemoryStore by default. func (o *ClientOptions) SetStore(s Store) *ClientOptions
{ o.Store = s return o }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
options.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L224-L227
go
train
// SetKeepAlive will set the amount of time (in seconds) that the client // should wait before sending a PING request to the broker. This will // allow the client to know that a connection has not been lost with the // server.
func (o *ClientOptions) SetKeepAlive(k time.Duration) *ClientOptions
// SetKeepAlive will set the amount of time (in seconds) that the client // should wait before sending a PING request to the broker. This will // allow the client to know that a connection has not been lost with the // server. func (o *ClientOptions) SetKeepAlive(k time.Duration) *ClientOptions
{ o.KeepAlive = int64(k / time.Second) return o }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
options.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L232-L235
go
train
// SetPingTimeout will set the amount of time (in seconds) that the client // will wait after sending a PING request to the broker, before deciding // that the connection has been lost. Default is 10 seconds.
func (o *ClientOptions) SetPingTimeout(k time.Duration) *ClientOptions
// SetPingTimeout will set the amount of time (in seconds) that the client // will wait after sending a PING request to the broker, before deciding // that the connection has been lost. Default is 10 seconds. func (o *ClientOptions) SetPingTimeout(k time.Duration) *ClientOptions
{ o.PingTimeout = k return o }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
options.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L239-L245
go
train
// SetProtocolVersion sets the MQTT version to be used to connect to the // broker. Legitimate values are currently 3 - MQTT 3.1 or 4 - MQTT 3.1.1
func (o *ClientOptions) SetProtocolVersion(pv uint) *ClientOptions
// SetProtocolVersion sets the MQTT version to be used to connect to the // broker. Legitimate values are currently 3 - MQTT 3.1 or 4 - MQTT 3.1.1 func (o *ClientOptions) SetProtocolVersion(pv uint) *ClientOptions
{ if (pv >= 3 && pv <= 4) || (pv > 0x80) { o.ProtocolVersion = pv o.protocolVersionExplicit = true } return o }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
options.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L257-L260
go
train
// SetWill accepts a string will message to be set. When the client connects, // it will give this will message to the broker, which will then publish the // provided payload (the will) to any clients that are subscribed to the provided // topic.
func (o *ClientOptions) SetWill(topic string, payload string, qos byte, retained bool) *ClientOptions
// SetWill accepts a string will message to be set. When the client connects, // it will give this will message to the broker, which will then publish the // provided payload (the will) to any clients that are subscribed to the provided // topic. func (o *ClientOptions) SetWill(topic string, payload string, qos byte, retained bool) *ClientOptions
{ o.SetBinaryWill(topic, []byte(payload), qos, retained) return o }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
options.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L266-L273
go
train
// SetBinaryWill accepts a []byte will message to be set. When the client connects, // it will give this will message to the broker, which will then publish the // provided payload (the will) to any clients that are subscribed to the provided // topic.
func (o *ClientOptions) SetBinaryWill(topic string, payload []byte, qos byte, retained bool) *ClientOptions
// SetBinaryWill accepts a []byte will message to be set. When the client connects, // it will give this will message to the broker, which will then publish the // provided payload (the will) to any clients that are subscribed to the provided // topic. func (o *ClientOptions) SetBinaryWill(topic string, payload []byte, qos byte, retained bool) *ClientOptions
{ o.WillEnabled = true o.WillTopic = topic o.WillPayload = payload o.WillQos = qos o.WillRetained = retained return o }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
options.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L277-L280
go
train
// SetDefaultPublishHandler sets the MessageHandler that will be called when a message // is received that does not match any known subscriptions.
func (o *ClientOptions) SetDefaultPublishHandler(defaultHandler MessageHandler) *ClientOptions
// SetDefaultPublishHandler sets the MessageHandler that will be called when a message // is received that does not match any known subscriptions. func (o *ClientOptions) SetDefaultPublishHandler(defaultHandler MessageHandler) *ClientOptions
{ o.DefaultPublishHandler = defaultHandler return o }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
options.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L284-L287
go
train
// SetOnConnectHandler sets the function to be called when the client is connected. Both // at initial connection time and upon automatic reconnect.
func (o *ClientOptions) SetOnConnectHandler(onConn OnConnectHandler) *ClientOptions
// SetOnConnectHandler sets the function to be called when the client is connected. Both // at initial connection time and upon automatic reconnect. func (o *ClientOptions) SetOnConnectHandler(onConn OnConnectHandler) *ClientOptions
{ o.OnConnect = onConn return o }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
options.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L291-L294
go
train
// SetConnectionLostHandler will set the OnConnectionLost callback to be executed // in the case where the client unexpectedly loses connection with the MQTT broker.
func (o *ClientOptions) SetConnectionLostHandler(onLost ConnectionLostHandler) *ClientOptions
// SetConnectionLostHandler will set the OnConnectionLost callback to be executed // in the case where the client unexpectedly loses connection with the MQTT broker. func (o *ClientOptions) SetConnectionLostHandler(onLost ConnectionLostHandler) *ClientOptions
{ o.OnConnectionLost = onLost return o }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
options.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L298-L301
go
train
// SetWriteTimeout puts a limit on how long a mqtt publish should block until it unblocks with a // timeout error. A duration of 0 never times out. Default 30 seconds
func (o *ClientOptions) SetWriteTimeout(t time.Duration) *ClientOptions
// SetWriteTimeout puts a limit on how long a mqtt publish should block until it unblocks with a // timeout error. A duration of 0 never times out. Default 30 seconds func (o *ClientOptions) SetWriteTimeout(t time.Duration) *ClientOptions
{ o.WriteTimeout = t return o }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
options.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L306-L309
go
train
// SetConnectTimeout limits how long the client will wait when trying to open a connection // to an MQTT server before timeing out and erroring the attempt. A duration of 0 never times out. // Default 30 seconds. Currently only operational on TCP/TLS connections.
func (o *ClientOptions) SetConnectTimeout(t time.Duration) *ClientOptions
// SetConnectTimeout limits how long the client will wait when trying to open a connection // to an MQTT server before timeing out and erroring the attempt. A duration of 0 never times out. // Default 30 seconds. Currently only operational on TCP/TLS connections. func (o *ClientOptions) SetConnectTimeout(t time.Duration) *ClientOptions
{ o.ConnectTimeout = t return o }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
options.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L313-L316
go
train
// SetMaxReconnectInterval sets the maximum time that will be waited between reconnection attempts // when connection is lost
func (o *ClientOptions) SetMaxReconnectInterval(t time.Duration) *ClientOptions
// SetMaxReconnectInterval sets the maximum time that will be waited between reconnection attempts // when connection is lost func (o *ClientOptions) SetMaxReconnectInterval(t time.Duration) *ClientOptions
{ o.MaxReconnectInterval = t return o }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
options.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L321-L324
go
train
// SetAutoReconnect sets whether the automatic reconnection logic should be used // when the connection is lost, even if disabled the ConnectionLostHandler is still // called
func (o *ClientOptions) SetAutoReconnect(a bool) *ClientOptions
// SetAutoReconnect sets whether the automatic reconnection logic should be used // when the connection is lost, even if disabled the ConnectionLostHandler is still // called func (o *ClientOptions) SetAutoReconnect(a bool) *ClientOptions
{ o.AutoReconnect = a return o }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
options.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L330-L333
go
train
// SetMessageChannelDepth sets the size of the internal queue that holds messages while the // client is temporairily offline, allowing the application to publish when the client is // reconnecting. This setting is only valid if AutoReconnect is set to true, it is otherwise // ignored.
func (o *ClientOptions) SetMessageChannelDepth(s uint) *ClientOptions
// SetMessageChannelDepth sets the size of the internal queue that holds messages while the // client is temporairily offline, allowing the application to publish when the client is // reconnecting. This setting is only valid if AutoReconnect is set to true, it is otherwise // ignored. func (o *ClientOptions) SetMessageChannelDepth(s uint) *ClientOptions
{ o.MessageChannelDepth = s return o }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
options.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options.go#L337-L340
go
train
// SetHTTPHeaders sets the additional HTTP headers that will be sent in the WebSocket // opening handshake.
func (o *ClientOptions) SetHTTPHeaders(h http.Header) *ClientOptions
// SetHTTPHeaders sets the additional HTTP headers that will be sent in the WebSocket // opening handshake. func (o *ClientOptions) SetHTTPHeaders(h http.Header) *ClientOptions
{ o.HTTPHeaders = h return o }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
net.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/net.go#L123-L161
go
train
// actually read incoming messages off the wire // send Message object into ibound channel
func incoming(c *client)
// actually read incoming messages off the wire // send Message object into ibound channel func incoming(c *client)
{ var err error var cp packets.ControlPacket defer c.workers.Done() DEBUG.Println(NET, "incoming started") for { if cp, err = packets.ReadPacket(c.conn); err != nil { break } DEBUG.Println(NET, "Received Message") select { case c.ibound <- cp: // Notify keepalive logic that we recently received a packet if c.options.KeepAlive != 0 { c.lastReceived.Store(time.Now()) } case <-c.stop: // This avoids a deadlock should a message arrive while shutting down. // In that case the "reader" of c.ibound might already be gone WARN.Println(NET, "incoming dropped a received message during shutdown") break } } // We received an error on read. // If disconnect is in progress, swallow error and return select { case <-c.stop: DEBUG.Println(NET, "incoming stopped") return // Not trying to disconnect, send the error to the errors channel default: ERROR.Println(NET, "incoming stopped with error", err) signalError(c.errors, err) return } }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
net.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/net.go#L233-L314
go
train
// receive Message objects on ibound // store messages if necessary // send replies on obound // delete messages from store if necessary
func alllogic(c *client)
// receive Message objects on ibound // store messages if necessary // send replies on obound // delete messages from store if necessary func alllogic(c *client)
{ defer c.workers.Done() DEBUG.Println(NET, "logic started") for { DEBUG.Println(NET, "logic waiting for msg on ibound") select { case msg := <-c.ibound: DEBUG.Println(NET, "logic got msg on ibound") persistInbound(c.persist, msg) switch m := msg.(type) { case *packets.PingrespPacket: DEBUG.Println(NET, "received pingresp") atomic.StoreInt32(&c.pingOutstanding, 0) case *packets.SubackPacket: DEBUG.Println(NET, "received suback, id:", m.MessageID) token := c.getToken(m.MessageID) switch t := token.(type) { case *SubscribeToken: DEBUG.Println(NET, "granted qoss", m.ReturnCodes) for i, qos := range m.ReturnCodes { t.subResult[t.subs[i]] = qos } } token.flowComplete() c.freeID(m.MessageID) case *packets.UnsubackPacket: DEBUG.Println(NET, "received unsuback, id:", m.MessageID) c.getToken(m.MessageID).flowComplete() c.freeID(m.MessageID) case *packets.PublishPacket: DEBUG.Println(NET, "received publish, msgId:", m.MessageID) DEBUG.Println(NET, "putting msg on onPubChan") switch m.Qos { case 2: c.incomingPubChan <- m DEBUG.Println(NET, "done putting msg on incomingPubChan") case 1: c.incomingPubChan <- m DEBUG.Println(NET, "done putting msg on incomingPubChan") case 0: select { case c.incomingPubChan <- m: case <-c.stop: } DEBUG.Println(NET, "done putting msg on incomingPubChan") } case *packets.PubackPacket: DEBUG.Println(NET, "received puback, id:", m.MessageID) // c.receipts.get(msg.MsgId()) <- Receipt{} // c.receipts.end(msg.MsgId()) c.getToken(m.MessageID).flowComplete() c.freeID(m.MessageID) case *packets.PubrecPacket: DEBUG.Println(NET, "received pubrec, id:", m.MessageID) prel := packets.NewControlPacket(packets.Pubrel).(*packets.PubrelPacket) prel.MessageID = m.MessageID select { case c.oboundP <- &PacketAndToken{p: prel, t: nil}: case <-c.stop: } case *packets.PubrelPacket: DEBUG.Println(NET, "received pubrel, id:", m.MessageID) pc := packets.NewControlPacket(packets.Pubcomp).(*packets.PubcompPacket) pc.MessageID = m.MessageID persistOutbound(c.persist, pc) select { case c.oboundP <- &PacketAndToken{p: pc, t: nil}: case <-c.stop: } case *packets.PubcompPacket: DEBUG.Println(NET, "received pubcomp, id:", m.MessageID) c.getToken(m.MessageID).flowComplete() c.freeID(m.MessageID) } case <-c.stop: WARN.Println(NET, "logic stopped") return } } }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
token.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/token.go#L66-L81
go
train
// WaitTimeout takes a time.Duration to wait for the flow associated with the // Token to complete, returns true if it returned before the timeout or // returns false if the timeout occurred. In the case of a timeout the Token // does not have an error set in case the caller wishes to wait again
func (b *baseToken) WaitTimeout(d time.Duration) bool
// WaitTimeout takes a time.Duration to wait for the flow associated with the // Token to complete, returns true if it returned before the timeout or // returns false if the timeout occurred. In the case of a timeout the Token // does not have an error set in case the caller wishes to wait again func (b *baseToken) WaitTimeout(d time.Duration) bool
{ b.m.Lock() defer b.m.Unlock() timer := time.NewTimer(d) select { case <-b.complete: if !timer.Stop() { <-timer.C } return true case <-timer.C: } return false }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
token.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/token.go#L130-L134
go
train
// ReturnCode returns the acknowlegement code in the connack sent // in response to a Connect()
func (c *ConnectToken) ReturnCode() byte
// ReturnCode returns the acknowlegement code in the connack sent // in response to a Connect() func (c *ConnectToken) ReturnCode() byte
{ c.m.RLock() defer c.m.RUnlock() return c.returnCode }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
token.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/token.go#L138-L142
go
train
// SessionPresent returns a bool representing the value of the // session present field in the connack sent in response to a Connect()
func (c *ConnectToken) SessionPresent() bool
// SessionPresent returns a bool representing the value of the // session present field in the connack sent in response to a Connect() func (c *ConnectToken) SessionPresent() bool
{ c.m.RLock() defer c.m.RUnlock() return c.sessionPresent }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
token.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/token.go#L168-L172
go
train
// Result returns a map of topics that were subscribed to along with // the matching return code from the broker. This is either the Qos // value of the subscription or an error code.
func (s *SubscribeToken) Result() map[string]byte
// Result returns a map of topics that were subscribed to along with // the matching return code from the broker. This is either the Qos // value of the subscription or an error code. func (s *SubscribeToken) Result() map[string]byte
{ s.m.RLock() defer s.m.RUnlock() return s.subResult }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
packets/unsuback.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/packets/unsuback.go#L34-L39
go
train
//Unpack decodes the details of a ControlPacket after the fixed //header has been read
func (ua *UnsubackPacket) Unpack(b io.Reader) error
//Unpack decodes the details of a ControlPacket after the fixed //header has been read func (ua *UnsubackPacket) Unpack(b io.Reader) error
{ var err error ua.MessageID, err = decodeUint16(b) return err }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
options_reader.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/options_reader.go#L30-L39
go
train
//Servers returns a slice of the servers defined in the clientoptions
func (r *ClientOptionsReader) Servers() []*url.URL
//Servers returns a slice of the servers defined in the clientoptions func (r *ClientOptionsReader) Servers() []*url.URL
{ s := make([]*url.URL, len(r.options.Servers)) for i, u := range r.options.Servers { nu := *u s[i] = &nu } return s }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
memstore.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/memstore.go#L35-L41
go
train
// NewMemoryStore returns a pointer to a new instance of // MemoryStore, the instance is not initialized and ready to // use until Open() has been called on it.
func NewMemoryStore() *MemoryStore
// NewMemoryStore returns a pointer to a new instance of // MemoryStore, the instance is not initialized and ready to // use until Open() has been called on it. func NewMemoryStore() *MemoryStore
{ store := &MemoryStore{ messages: make(map[string]packets.ControlPacket), opened: false, } return store }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
memstore.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/memstore.go#L44-L49
go
train
// Open initializes a MemoryStore instance.
func (store *MemoryStore) Open()
// Open initializes a MemoryStore instance. func (store *MemoryStore) Open()
{ store.Lock() defer store.Unlock() store.opened = true DEBUG.Println(STR, "memorystore initialized") }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
memstore.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/memstore.go#L53-L61
go
train
// Put takes a key and a pointer to a Message and stores the // message.
func (store *MemoryStore) Put(key string, message packets.ControlPacket)
// Put takes a key and a pointer to a Message and stores the // message. func (store *MemoryStore) Put(key string, message packets.ControlPacket)
{ store.Lock() defer store.Unlock() if !store.opened { ERROR.Println(STR, "Trying to use memory store, but not open") return } store.messages[key] = message }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
memstore.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/memstore.go#L65-L80
go
train
// Get takes a key and looks in the store for a matching Message // returning either the Message pointer or nil.
func (store *MemoryStore) Get(key string) packets.ControlPacket
// Get takes a key and looks in the store for a matching Message // returning either the Message pointer or nil. func (store *MemoryStore) Get(key string) packets.ControlPacket
{ store.RLock() defer store.RUnlock() if !store.opened { ERROR.Println(STR, "Trying to use memory store, but not open") return nil } mid := mIDFromKey(key) m := store.messages[key] if m == nil { CRITICAL.Println(STR, "memorystore get: message", mid, "not found") } else { DEBUG.Println(STR, "memorystore get: message", mid, "found") } return m }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
memstore.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/memstore.go#L84-L96
go
train
// All returns a slice of strings containing all the keys currently // in the MemoryStore.
func (store *MemoryStore) All() []string
// All returns a slice of strings containing all the keys currently // in the MemoryStore. func (store *MemoryStore) All() []string
{ store.RLock() defer store.RUnlock() if !store.opened { ERROR.Println(STR, "Trying to use memory store, but not open") return nil } keys := []string{} for k := range store.messages { keys = append(keys, k) } return keys }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
memstore.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/memstore.go#L100-L115
go
train
// Del takes a key, searches the MemoryStore and if the key is found // deletes the Message pointer associated with it.
func (store *MemoryStore) Del(key string)
// Del takes a key, searches the MemoryStore and if the key is found // deletes the Message pointer associated with it. func (store *MemoryStore) Del(key string)
{ store.Lock() defer store.Unlock() if !store.opened { ERROR.Println(STR, "Trying to use memory store, but not open") return } mid := mIDFromKey(key) m := store.messages[key] if m == nil { WARN.Println(STR, "memorystore del: message", mid, "not found") } else { delete(store.messages, key) DEBUG.Println(STR, "memorystore del: message", mid, "was deleted") } }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
packets/pubrec.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/packets/pubrec.go#L34-L39
go
train
//Unpack decodes the details of a ControlPacket after the fixed //header has been read
func (pr *PubrecPacket) Unpack(b io.Reader) error
//Unpack decodes the details of a ControlPacket after the fixed //header has been read func (pr *PubrecPacket) Unpack(b io.Reader) error
{ var err error pr.MessageID, err = decodeUint16(b) return err }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
packets/pubrec.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/packets/pubrec.go#L43-L45
go
train
//Details returns a Details struct containing the Qos and //MessageID of this ControlPacket
func (pr *PubrecPacket) Details() Details
//Details returns a Details struct containing the Qos and //MessageID of this ControlPacket func (pr *PubrecPacket) Details() Details
{ return Details{Qos: pr.Qos, MessageID: pr.MessageID} }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
client.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/client.go#L122-L147
go
train
// NewClient will create an MQTT v3.1.1 client with all of the options specified // in the provided ClientOptions. The client must have the Connect method called // on it before it may be used. This is to make sure resources (such as a net // connection) are created before the application is actually ready.
func NewClient(o *ClientOptions) Client
// NewClient will create an MQTT v3.1.1 client with all of the options specified // in the provided ClientOptions. The client must have the Connect method called // on it before it may be used. This is to make sure resources (such as a net // connection) are created before the application is actually ready. func NewClient(o *ClientOptions) Client
{ c := &client{} c.options = *o if c.options.Store == nil { c.options.Store = NewMemoryStore() } switch c.options.ProtocolVersion { case 3, 4: c.options.protocolVersionExplicit = true case 0x83, 0x84: c.options.protocolVersionExplicit = true default: c.options.ProtocolVersion = 4 c.options.protocolVersionExplicit = false } c.persist = c.options.Store c.status = disconnected c.messageIds = messageIds{index: make(map[uint16]tokenCompletor)} c.msgRouter, c.stopRouter = newRouter() c.msgRouter.setDefaultHandler(c.options.DefaultPublishHandler) if !c.options.AutoReconnect { c.options.MessageChannelDepth = 0 } return c }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
client.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/client.go#L152-L156
go
train
// AddRoute allows you to add a handler for messages on a specific topic // without making a subscription. For example having a different handler // for parts of a wildcard subscription
func (c *client) AddRoute(topic string, callback MessageHandler)
// AddRoute allows you to add a handler for messages on a specific topic // without making a subscription. For example having a different handler // for parts of a wildcard subscription func (c *client) AddRoute(topic string, callback MessageHandler)
{ if callback != nil { c.msgRouter.addRoute(topic, callback) } }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
client.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/client.go#L160-L172
go
train
// IsConnected returns a bool signifying whether // the client is connected or not.
func (c *client) IsConnected() bool
// IsConnected returns a bool signifying whether // the client is connected or not. func (c *client) IsConnected() bool
{ c.RLock() defer c.RUnlock() status := atomic.LoadUint32(&c.status) switch { case status == connected: return true case c.options.AutoReconnect && status > connecting: return true default: return false } }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
client.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/client.go#L176-L186
go
train
// IsConnectionOpen return a bool signifying whether the client has an active // connection to mqtt broker, i.e not in disconnected or reconnect mode
func (c *client) IsConnectionOpen() bool
// IsConnectionOpen return a bool signifying whether the client has an active // connection to mqtt broker, i.e not in disconnected or reconnect mode func (c *client) IsConnectionOpen() bool
{ c.RLock() defer c.RUnlock() status := atomic.LoadUint32(&c.status) switch { case status == connected: return true default: return false } }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
client.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/client.go#L208-L335
go
train
// Connect will create a connection to the message broker, by default // it will attempt to connect at v3.1.1 and auto retry at v3.1 if that // fails
func (c *client) Connect() Token
// Connect will create a connection to the message broker, by default // it will attempt to connect at v3.1.1 and auto retry at v3.1 if that // fails func (c *client) Connect() Token
{ var err error t := newToken(packets.Connect).(*ConnectToken) DEBUG.Println(CLI, "Connect()") c.obound = make(chan *PacketAndToken, c.options.MessageChannelDepth) c.oboundP = make(chan *PacketAndToken, c.options.MessageChannelDepth) c.ibound = make(chan packets.ControlPacket) go func() { c.persist.Open() c.setConnected(connecting) c.errors = make(chan error, 1) c.stop = make(chan struct{}) var rc byte protocolVersion := c.options.ProtocolVersion if len(c.options.Servers) == 0 { t.setError(fmt.Errorf("No servers defined to connect to")) return } for _, broker := range c.options.Servers { cm := newConnectMsgFromOptions(&c.options, broker) c.options.ProtocolVersion = protocolVersion CONN: DEBUG.Println(CLI, "about to write new connect msg") c.conn, err = openConnection(broker, c.options.TLSConfig, c.options.ConnectTimeout, c.options.HTTPHeaders) if err == nil { DEBUG.Println(CLI, "socket connected to broker") switch c.options.ProtocolVersion { case 3: DEBUG.Println(CLI, "Using MQTT 3.1 protocol") cm.ProtocolName = "MQIsdp" cm.ProtocolVersion = 3 case 0x83: DEBUG.Println(CLI, "Using MQTT 3.1b protocol") cm.ProtocolName = "MQIsdp" cm.ProtocolVersion = 0x83 case 0x84: DEBUG.Println(CLI, "Using MQTT 3.1.1b protocol") cm.ProtocolName = "MQTT" cm.ProtocolVersion = 0x84 default: DEBUG.Println(CLI, "Using MQTT 3.1.1 protocol") c.options.ProtocolVersion = 4 cm.ProtocolName = "MQTT" cm.ProtocolVersion = 4 } cm.Write(c.conn) rc, t.sessionPresent = c.connect() if rc != packets.Accepted { if c.conn != nil { c.conn.Close() c.conn = nil } //if the protocol version was explicitly set don't do any fallback if c.options.protocolVersionExplicit { ERROR.Println(CLI, "Connecting to", broker, "CONNACK was not CONN_ACCEPTED, but rather", packets.ConnackReturnCodes[rc]) continue } if c.options.ProtocolVersion == 4 { DEBUG.Println(CLI, "Trying reconnect using MQTT 3.1 protocol") c.options.ProtocolVersion = 3 goto CONN } } break } else { ERROR.Println(CLI, err.Error()) WARN.Println(CLI, "failed to connect to broker, trying next") rc = packets.ErrNetworkError } } if c.conn == nil { ERROR.Println(CLI, "Failed to connect to a broker") c.setConnected(disconnected) c.persist.Close() t.returnCode = rc if rc != packets.ErrNetworkError { t.setError(packets.ConnErrors[rc]) } else { t.setError(fmt.Errorf("%s : %s", packets.ConnErrors[rc], err)) } return } c.options.protocolVersionExplicit = true if c.options.KeepAlive != 0 { atomic.StoreInt32(&c.pingOutstanding, 0) c.lastReceived.Store(time.Now()) c.lastSent.Store(time.Now()) c.workers.Add(1) go keepalive(c) } c.incomingPubChan = make(chan *packets.PublishPacket, c.options.MessageChannelDepth) c.msgRouter.matchAndDispatch(c.incomingPubChan, c.options.Order, c) c.setConnected(connected) DEBUG.Println(CLI, "client is connected") if c.options.OnConnect != nil { go c.options.OnConnect(c) } c.workers.Add(4) go errorWatch(c) go alllogic(c) go outgoing(c) go incoming(c) // Take care of any messages in the store if c.options.CleanSession == false { c.resume(c.options.ResumeSubs) } else { c.persist.Reset() } DEBUG.Println(CLI, "exit startClient") t.flowComplete() }() return t }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
client.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/client.go#L338-L434
go
train
// internal function used to reconnect the client when it loses its connection
func (c *client) reconnect()
// internal function used to reconnect the client when it loses its connection func (c *client) reconnect()
{ DEBUG.Println(CLI, "enter reconnect") var ( err error rc = byte(1) sleep = time.Duration(1 * time.Second) ) for rc != 0 && atomic.LoadUint32(&c.status) != disconnected { for _, broker := range c.options.Servers { cm := newConnectMsgFromOptions(&c.options, broker) DEBUG.Println(CLI, "about to write new connect msg") c.Lock() c.conn, err = openConnection(broker, c.options.TLSConfig, c.options.ConnectTimeout, c.options.HTTPHeaders) c.Unlock() if err == nil { DEBUG.Println(CLI, "socket connected to broker") switch c.options.ProtocolVersion { case 0x83: DEBUG.Println(CLI, "Using MQTT 3.1b protocol") cm.ProtocolName = "MQIsdp" cm.ProtocolVersion = 0x83 case 0x84: DEBUG.Println(CLI, "Using MQTT 3.1.1b protocol") cm.ProtocolName = "MQTT" cm.ProtocolVersion = 0x84 case 3: DEBUG.Println(CLI, "Using MQTT 3.1 protocol") cm.ProtocolName = "MQIsdp" cm.ProtocolVersion = 3 default: DEBUG.Println(CLI, "Using MQTT 3.1.1 protocol") cm.ProtocolName = "MQTT" cm.ProtocolVersion = 4 } cm.Write(c.conn) rc, _ = c.connect() if rc != packets.Accepted { c.conn.Close() c.conn = nil //if the protocol version was explicitly set don't do any fallback if c.options.protocolVersionExplicit { ERROR.Println(CLI, "Connecting to", broker, "CONNACK was not Accepted, but rather", packets.ConnackReturnCodes[rc]) continue } } break } else { ERROR.Println(CLI, err.Error()) WARN.Println(CLI, "failed to connect to broker, trying next") rc = packets.ErrNetworkError } } if rc != 0 { DEBUG.Println(CLI, "Reconnect failed, sleeping for", int(sleep.Seconds()), "seconds") time.Sleep(sleep) if sleep < c.options.MaxReconnectInterval { sleep *= 2 } if sleep > c.options.MaxReconnectInterval { sleep = c.options.MaxReconnectInterval } } } // Disconnect() must have been called while we were trying to reconnect. if c.connectionStatus() == disconnected { DEBUG.Println(CLI, "Client moved to disconnected state while reconnecting, abandoning reconnect") return } c.stop = make(chan struct{}) if c.options.KeepAlive != 0 { atomic.StoreInt32(&c.pingOutstanding, 0) c.lastReceived.Store(time.Now()) c.lastSent.Store(time.Now()) c.workers.Add(1) go keepalive(c) } c.setConnected(connected) DEBUG.Println(CLI, "client is reconnected") if c.options.OnConnect != nil { go c.options.OnConnect(c) } c.workers.Add(4) go errorWatch(c) go alllogic(c) go outgoing(c) go incoming(c) c.resume(false) }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
client.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/client.go#L440-L461
go
train
// This function is only used for receiving a connack // when the connection is first started. // This prevents receiving incoming data while resume // is in progress if clean session is false.
func (c *client) connect() (byte, bool)
// This function is only used for receiving a connack // when the connection is first started. // This prevents receiving incoming data while resume // is in progress if clean session is false. func (c *client) connect() (byte, bool)
{ DEBUG.Println(NET, "connect started") ca, err := packets.ReadPacket(c.conn) if err != nil { ERROR.Println(NET, "connect got error", err) return packets.ErrNetworkError, false } if ca == nil { ERROR.Println(NET, "received nil packet") return packets.ErrNetworkError, false } msg, ok := ca.(*packets.ConnackPacket) if !ok { ERROR.Println(NET, "received msg that was not CONNACK") return packets.ErrNetworkError, false } DEBUG.Println(NET, "received connack") return msg.ReturnCode, msg.SessionPresent }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
client.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/client.go#L466-L484
go
train
// Disconnect will end the connection with the server, but not before waiting // the specified number of milliseconds to wait for existing work to be // completed.
func (c *client) Disconnect(quiesce uint)
// Disconnect will end the connection with the server, but not before waiting // the specified number of milliseconds to wait for existing work to be // completed. func (c *client) Disconnect(quiesce uint)
{ status := atomic.LoadUint32(&c.status) if status == connected { DEBUG.Println(CLI, "disconnecting") c.setConnected(disconnected) dm := packets.NewControlPacket(packets.Disconnect).(*packets.DisconnectPacket) dt := newToken(packets.Disconnect) c.oboundP <- &PacketAndToken{p: dm, t: dt} // wait for work to finish, or quiesce time consumed dt.WaitTimeout(time.Duration(quiesce) * time.Millisecond) } else { WARN.Println(CLI, "Disconnect() called but not connected (disconnected/reconnecting)") c.setConnected(disconnected) } c.disconnect() }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
client.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/client.go#L568-L605
go
train
// Publish will publish a message with the specified QoS and content // to the specified topic. // Returns a token to track delivery of the message to the broker
func (c *client) Publish(topic string, qos byte, retained bool, payload interface{}) Token
// Publish will publish a message with the specified QoS and content // to the specified topic. // Returns a token to track delivery of the message to the broker func (c *client) Publish(topic string, qos byte, retained bool, payload interface{}) Token
{ token := newToken(packets.Publish).(*PublishToken) DEBUG.Println(CLI, "enter Publish") switch { case !c.IsConnected(): token.setError(ErrNotConnected) return token case c.connectionStatus() == reconnecting && qos == 0: token.flowComplete() return token } pub := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) pub.Qos = qos pub.TopicName = topic pub.Retain = retained switch payload.(type) { case string: pub.Payload = []byte(payload.(string)) case []byte: pub.Payload = payload.([]byte) default: token.setError(fmt.Errorf("Unknown payload type")) return token } if pub.Qos != 0 && pub.MessageID == 0 { pub.MessageID = c.getID(token) token.messageID = pub.MessageID } persistOutbound(c.persist, pub) if c.connectionStatus() == reconnecting { DEBUG.Println(CLI, "storing publish message (reconnecting), topic:", topic) } else { DEBUG.Println(CLI, "sending publish message, topic:", topic) c.obound <- &PacketAndToken{p: pub, t: token} } return token }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
client.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/client.go#L669-L723
go
train
// Load all stored messages and resend them // Call this to ensure QOS > 1,2 even after an application crash
func (c *client) resume(subscription bool)
// Load all stored messages and resend them // Call this to ensure QOS > 1,2 even after an application crash func (c *client) resume(subscription bool)
{ storedKeys := c.persist.All() for _, key := range storedKeys { packet := c.persist.Get(key) if packet == nil { continue } details := packet.Details() if isKeyOutbound(key) { switch packet.(type) { case *packets.SubscribePacket: if subscription { DEBUG.Println(STR, fmt.Sprintf("loaded pending subscribe (%d)", details.MessageID)) token := newToken(packets.Subscribe).(*SubscribeToken) c.oboundP <- &PacketAndToken{p: packet, t: token} } case *packets.UnsubscribePacket: if subscription { DEBUG.Println(STR, fmt.Sprintf("loaded pending unsubscribe (%d)", details.MessageID)) token := newToken(packets.Unsubscribe).(*UnsubscribeToken) c.oboundP <- &PacketAndToken{p: packet, t: token} } case *packets.PubrelPacket: DEBUG.Println(STR, fmt.Sprintf("loaded pending pubrel (%d)", details.MessageID)) select { case c.oboundP <- &PacketAndToken{p: packet, t: nil}: case <-c.stop: } case *packets.PublishPacket: token := newToken(packets.Publish).(*PublishToken) token.messageID = details.MessageID c.claimID(token, details.MessageID) DEBUG.Println(STR, fmt.Sprintf("loaded pending publish (%d)", details.MessageID)) DEBUG.Println(STR, details) c.obound <- &PacketAndToken{p: packet, t: token} default: ERROR.Println(STR, "invalid message type in store (discarded)") c.persist.Del(key) } } else { switch packet.(type) { case *packets.PubrelPacket, *packets.PublishPacket: DEBUG.Println(STR, fmt.Sprintf("loaded pending incomming (%d)", details.MessageID)) select { case c.ibound <- packet: case <-c.stop: } default: ERROR.Println(STR, "invalid message type in store (discarded)") c.persist.Del(key) } } } }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
client.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/client.go#L750-L753
go
train
// OptionsReader returns a ClientOptionsReader which is a copy of the clientoptions // in use by the client.
func (c *client) OptionsReader() ClientOptionsReader
// OptionsReader returns a ClientOptionsReader which is a copy of the clientoptions // in use by the client. func (c *client) OptionsReader() ClientOptionsReader
{ r := ClientOptionsReader{options: &c.options} return r }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
topic.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/topic.go#L52-L64
go
train
// Topic Names and Topic Filters // The MQTT v3.1.1 spec clarifies a number of ambiguities with regard // to the validity of Topic strings. // - A Topic must be between 1 and 65535 bytes. // - A Topic is case sensitive. // - A Topic may contain whitespace. // - A Topic containing a leading forward slash is different than a Topic without. // - A Topic may be "/" (two levels, both empty string). // - A Topic must be UTF-8 encoded. // - A Topic may contain any number of levels. // - A Topic may contain an empty level (two forward slashes in a row). // - A TopicName may not contain a wildcard. // - A TopicFilter may only have a # (multi-level) wildcard as the last level. // - A TopicFilter may contain any number of + (single-level) wildcards. // - A TopicFilter with a # will match the absense of a level // Example: a subscription to "foo/#" will match messages published to "foo".
func validateSubscribeMap(subs map[string]byte) ([]string, []byte, error)
// Topic Names and Topic Filters // The MQTT v3.1.1 spec clarifies a number of ambiguities with regard // to the validity of Topic strings. // - A Topic must be between 1 and 65535 bytes. // - A Topic is case sensitive. // - A Topic may contain whitespace. // - A Topic containing a leading forward slash is different than a Topic without. // - A Topic may be "/" (two levels, both empty string). // - A Topic must be UTF-8 encoded. // - A Topic may contain any number of levels. // - A Topic may contain an empty level (two forward slashes in a row). // - A TopicName may not contain a wildcard. // - A TopicFilter may only have a # (multi-level) wildcard as the last level. // - A TopicFilter may contain any number of + (single-level) wildcards. // - A TopicFilter with a # will match the absense of a level // Example: a subscription to "foo/#" will match messages published to "foo". func validateSubscribeMap(subs map[string]byte) ([]string, []byte, error)
{ var topics []string var qoss []byte for topic, qos := range subs { if err := validateTopicAndQos(topic, qos); err != nil { return nil, nil, err } topics = append(topics, topic) qoss = append(qoss, qos) } return topics, qoss, nil }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
packets/pubrel.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/packets/pubrel.go#L43-L45
go
train
//Details returns a Details struct containing the Qos and //MessageID of this ControlPacket
func (pr *PubrelPacket) Details() Details
//Details returns a Details struct containing the Qos and //MessageID of this ControlPacket func (pr *PubrelPacket) Details() Details
{ return Details{Qos: pr.Qos, MessageID: pr.MessageID} }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
packets/suback.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/packets/suback.go#L39-L54
go
train
//Unpack decodes the details of a ControlPacket after the fixed //header has been read
func (sa *SubackPacket) Unpack(b io.Reader) error
//Unpack decodes the details of a ControlPacket after the fixed //header has been read func (sa *SubackPacket) Unpack(b io.Reader) error
{ var qosBuffer bytes.Buffer var err error sa.MessageID, err = decodeUint16(b) if err != nil { return err } _, err = qosBuffer.ReadFrom(b) if err != nil { return err } sa.ReturnCodes = qosBuffer.Bytes() return nil }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
packets/connack.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/packets/connack.go#L40-L49
go
train
//Unpack decodes the details of a ControlPacket after the fixed //header has been read
func (ca *ConnackPacket) Unpack(b io.Reader) error
//Unpack decodes the details of a ControlPacket after the fixed //header has been read func (ca *ConnackPacket) Unpack(b io.Reader) error
{ flags, err := decodeByte(b) if err != nil { return err } ca.SessionPresent = 1&flags > 0 ca.ReturnCode, err = decodeByte(b) return err }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
packets/unsubscribe.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/packets/unsubscribe.go#L41-L53
go
train
//Unpack decodes the details of a ControlPacket after the fixed //header has been read
func (u *UnsubscribePacket) Unpack(b io.Reader) error
//Unpack decodes the details of a ControlPacket after the fixed //header has been read func (u *UnsubscribePacket) Unpack(b io.Reader) error
{ var err error u.MessageID, err = decodeUint16(b) if err != nil { return err } for topic, err := decodeString(b); err == nil && topic != ""; topic, err = decodeString(b) { u.Topics = append(u.Topics, topic) } return err }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
packets/subscribe.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/packets/subscribe.go#L44-L66
go
train
//Unpack decodes the details of a ControlPacket after the fixed //header has been read
func (s *SubscribePacket) Unpack(b io.Reader) error
//Unpack decodes the details of a ControlPacket after the fixed //header has been read func (s *SubscribePacket) Unpack(b io.Reader) error
{ var err error s.MessageID, err = decodeUint16(b) if err != nil { return err } payloadLength := s.FixedHeader.RemainingLength - 2 for payloadLength > 0 { topic, err := decodeString(b) if err != nil { return err } s.Topics = append(s.Topics, topic) qos, err := decodeByte(b) if err != nil { return err } s.Qoss = append(s.Qoss, qos) payloadLength -= 2 + len(topic) + 1 //2 bytes of string length, plus string, plus 1 byte for Qos } return nil }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
packets/publish.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/packets/publish.go#L46-L70
go
train
//Unpack decodes the details of a ControlPacket after the fixed //header has been read
func (p *PublishPacket) Unpack(b io.Reader) error
//Unpack decodes the details of a ControlPacket after the fixed //header has been read func (p *PublishPacket) Unpack(b io.Reader) error
{ var payloadLength = p.FixedHeader.RemainingLength var err error p.TopicName, err = decodeString(b) if err != nil { return err } if p.Qos > 0 { p.MessageID, err = decodeUint16(b) if err != nil { return err } payloadLength -= len(p.TopicName) + 4 } else { payloadLength -= len(p.TopicName) + 2 } if payloadLength < 0 { return fmt.Errorf("Error unpacking publish, payload length < 0") } p.Payload = make([]byte, payloadLength) _, err = b.Read(p.Payload) return err }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
packets/publish.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/packets/publish.go#L76-L82
go
train
//Copy creates a new PublishPacket with the same topic and payload //but an empty fixed header, useful for when you want to deliver //a message with different properties such as Qos but the same //content
func (p *PublishPacket) Copy() *PublishPacket
//Copy creates a new PublishPacket with the same topic and payload //but an empty fixed header, useful for when you want to deliver //a message with different properties such as Qos but the same //content func (p *PublishPacket) Copy() *PublishPacket
{ newP := NewControlPacket(Publish).(*PublishPacket) newP.TopicName = p.TopicName newP.Payload = p.Payload return newP }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
packets/publish.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/packets/publish.go#L86-L88
go
train
//Details returns a Details struct containing the Qos and //MessageID of this ControlPacket
func (p *PublishPacket) Details() Details
//Details returns a Details struct containing the Qos and //MessageID of this ControlPacket func (p *PublishPacket) Details() Details
{ return Details{Qos: p.Qos, MessageID: p.MessageID} }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
filestore.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/filestore.go#L46-L52
go
train
// NewFileStore will create a new FileStore which stores its messages in the // directory provided.
func NewFileStore(directory string) *FileStore
// NewFileStore will create a new FileStore which stores its messages in the // directory provided. func NewFileStore(directory string) *FileStore
{ store := &FileStore{ directory: directory, opened: false, } return store }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
filestore.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/filestore.go#L55-L72
go
train
// Open will allow the FileStore to be used.
func (store *FileStore) Open()
// Open will allow the FileStore to be used. func (store *FileStore) Open()
{ store.Lock() defer store.Unlock() // if no store directory was specified in ClientOpts, by default use the // current working directory if store.directory == "" { store.directory, _ = os.Getwd() } // if store dir exists, great, otherwise, create it if !exists(store.directory) { perms := os.FileMode(0770) merr := os.MkdirAll(store.directory, perms) chkerr(merr) } store.opened = true DEBUG.Println(STR, "store is opened at", store.directory) }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
filestore.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/filestore.go#L84-L96
go
train
// Put will put a message into the store, associated with the provided // key value.
func (store *FileStore) Put(key string, m packets.ControlPacket)
// Put will put a message into the store, associated with the provided // key value. func (store *FileStore) Put(key string, m packets.ControlPacket)
{ store.Lock() defer store.Unlock() if !store.opened { ERROR.Println(STR, "Trying to use file store, but not open") return } full := fullpath(store.directory, key) write(store.directory, key, m) if !exists(full) { ERROR.Println(STR, "file not created:", full) } }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
filestore.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/filestore.go#L100-L124
go
train
// Get will retrieve a message from the store, the one associated with // the provided key value.
func (store *FileStore) Get(key string) packets.ControlPacket
// Get will retrieve a message from the store, the one associated with // the provided key value. func (store *FileStore) Get(key string) packets.ControlPacket
{ store.RLock() defer store.RUnlock() if !store.opened { ERROR.Println(STR, "Trying to use file store, but not open") return nil } filepath := fullpath(store.directory, key) if !exists(filepath) { return nil } mfile, oerr := os.Open(filepath) chkerr(oerr) msg, rerr := packets.ReadPacket(mfile) chkerr(mfile.Close()) // Message was unreadable, return nil if rerr != nil { newpath := corruptpath(store.directory, key) WARN.Println(STR, "corrupted file detected:", rerr.Error(), "archived at:", newpath) os.Rename(filepath, newpath) return nil } return msg }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
filestore.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/filestore.go#L128-L132
go
train
// All will provide a list of all of the keys associated with messages // currenly residing in the FileStore.
func (store *FileStore) All() []string
// All will provide a list of all of the keys associated with messages // currenly residing in the FileStore. func (store *FileStore) All() []string
{ store.RLock() defer store.RUnlock() return store.all() }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
filestore.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/filestore.go#L136-L140
go
train
// Del will remove the persisted message associated with the provided // key from the FileStore.
func (store *FileStore) Del(key string)
// Del will remove the persisted message associated with the provided // key from the FileStore. func (store *FileStore) Del(key string)
{ store.Lock() defer store.Unlock() store.del(key) }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
filestore.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/filestore.go#L143-L150
go
train
// Reset will remove all persisted messages from the FileStore.
func (store *FileStore) Reset()
// Reset will remove all persisted messages from the FileStore. func (store *FileStore) Reset()
{ store.Lock() defer store.Unlock() WARN.Println(STR, "FileStore Reset") for _, key := range store.all() { store.del(key) } }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
filestore.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/filestore.go#L153-L177
go
train
// lockless
func (store *FileStore) all() []string
// lockless func (store *FileStore) all() []string
{ var err error var keys []string var files fileInfos if !store.opened { ERROR.Println(STR, "Trying to use file store, but not open") return nil } files, err = ioutil.ReadDir(store.directory) chkerr(err) sort.Sort(files) for _, f := range files { DEBUG.Println(STR, "file in All():", f.Name()) name := f.Name() if name[len(name)-4:len(name)] != msgExt { DEBUG.Println(STR, "skipping file, doesn't have right extension: ", name) continue } key := name[0 : len(name)-4] // remove file extension keys = append(keys, key) } return keys }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
filestore.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/filestore.go#L221-L231
go
train
// create file called "X.[messageid].tmp" located in the store // the contents of the file is the bytes of the message, then // rename it to "X.[messageid].msg", overwriting any existing // message with the same id // X will be 'i' for inbound messages, and O for outbound messages
func write(store, key string, m packets.ControlPacket)
// create file called "X.[messageid].tmp" located in the store // the contents of the file is the bytes of the message, then // rename it to "X.[messageid].msg", overwriting any existing // message with the same id // X will be 'i' for inbound messages, and O for outbound messages func write(store, key string, m packets.ControlPacket)
{ temppath := tmppath(store, key) f, err := os.Create(temppath) chkerr(err) werr := m.Write(f) chkerr(werr) cerr := f.Close() chkerr(cerr) rerr := os.Rename(temppath, fullpath(store, key)) chkerr(rerr) }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
router.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/router.go#L38-L61
go
train
// match takes a slice of strings which represent the route being tested having been split on '/' // separators, and a slice of strings representing the topic string in the published message, similarly // split. // The function determines if the topic string matches the route according to the MQTT topic rules // and returns a boolean of the outcome
func match(route []string, topic []string) bool
// match takes a slice of strings which represent the route being tested having been split on '/' // separators, and a slice of strings representing the topic string in the published message, similarly // split. // The function determines if the topic string matches the route according to the MQTT topic rules // and returns a boolean of the outcome func match(route []string, topic []string) bool
{ if len(route) == 0 { if len(topic) == 0 { return true } return false } if len(topic) == 0 { if route[0] == "#" { return true } return false } if route[0] == "#" { return true } if (route[0] == "+") || (route[0] == topic[0]) { return match(route[1:], topic[1:]) } return false }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
router.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/router.go#L69-L77
go
train
// removes $share and sharename when splitting the route to allow // shared subscription routes to correctly match the topic
func routeSplit(route string) []string
// removes $share and sharename when splitting the route to allow // shared subscription routes to correctly match the topic func routeSplit(route string) []string
{ var result []string if strings.HasPrefix(route, "$share") { result = strings.Split(route, "/")[2:] } else { result = strings.Split(route, "/") } return result }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
router.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/router.go#L81-L83
go
train
// match takes the topic string of the published message and does a basic compare to the // string of the current Route, if they match it returns true
func (r *route) match(topic string) bool
// match takes the topic string of the published message and does a basic compare to the // string of the current Route, if they match it returns true func (r *route) match(topic string) bool
{ return r.topic == topic || routeIncludesTopic(r.topic, topic) }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
router.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/router.go#L95-L99
go
train
// newRouter returns a new instance of a Router and channel which can be used to tell the Router // to stop
func newRouter() (*router, chan bool)
// newRouter returns a new instance of a Router and channel which can be used to tell the Router // to stop func newRouter() (*router, chan bool)
{ router := &router{routes: list.New(), messages: make(chan *packets.PublishPacket), stop: make(chan bool)} stop := router.stop return router, stop }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
router.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/router.go#L104-L115
go
train
// addRoute takes a topic string and MessageHandler callback. It looks in the current list of // routes to see if there is already a matching Route. If there is it replaces the current // callback with the new one. If not it add a new entry to the list of Routes.
func (r *router) addRoute(topic string, callback MessageHandler)
// addRoute takes a topic string and MessageHandler callback. It looks in the current list of // routes to see if there is already a matching Route. If there is it replaces the current // callback with the new one. If not it add a new entry to the list of Routes. func (r *router) addRoute(topic string, callback MessageHandler)
{ r.Lock() defer r.Unlock() for e := r.routes.Front(); e != nil; e = e.Next() { if e.Value.(*route).match(topic) { r := e.Value.(*route) r.callback = callback return } } r.routes.PushBack(&route{topic: topic, callback: callback}) }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
router.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/router.go#L119-L128
go
train
// deleteRoute takes a route string, looks for a matching Route in the list of Routes. If // found it removes the Route from the list.
func (r *router) deleteRoute(topic string)
// deleteRoute takes a route string, looks for a matching Route in the list of Routes. If // found it removes the Route from the list. func (r *router) deleteRoute(topic string)
{ r.Lock() defer r.Unlock() for e := r.routes.Front(); e != nil; e = e.Next() { if e.Value.(*route).match(topic) { r.routes.Remove(e) return } } }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
router.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/router.go#L132-L136
go
train
// setDefaultHandler assigns a default callback that will be called if no matching Route // is found for an incoming Publish.
func (r *router) setDefaultHandler(handler MessageHandler)
// setDefaultHandler assigns a default callback that will be called if no matching Route // is found for an incoming Publish. func (r *router) setDefaultHandler(handler MessageHandler)
{ r.Lock() defer r.Unlock() r.defaultHandler = handler }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
router.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/router.go#L142-L187
go
train
// matchAndDispatch takes a channel of Message pointers as input and starts a go routine that // takes messages off the channel, matches them against the internal route list and calls the // associated callback (or the defaultHandler, if one exists and no other route matched). If // anything is sent down the stop channel the function will end.
func (r *router) matchAndDispatch(messages <-chan *packets.PublishPacket, order bool, client *client)
// matchAndDispatch takes a channel of Message pointers as input and starts a go routine that // takes messages off the channel, matches them against the internal route list and calls the // associated callback (or the defaultHandler, if one exists and no other route matched). If // anything is sent down the stop channel the function will end. func (r *router) matchAndDispatch(messages <-chan *packets.PublishPacket, order bool, client *client)
{ go func() { for { select { case message := <-messages: sent := false r.RLock() m := messageFromPublish(message, client.ackFunc(message)) handlers := []MessageHandler{} for e := r.routes.Front(); e != nil; e = e.Next() { if e.Value.(*route).match(message.TopicName) { if order { handlers = append(handlers, e.Value.(*route).callback) } else { hd := e.Value.(*route).callback go func() { hd(client, m) m.Ack() }() } sent = true } } if !sent && r.defaultHandler != nil { if order { handlers = append(handlers, r.defaultHandler) } else { go func() { r.defaultHandler(client, m) m.Ack() }() } } r.RUnlock() for _, handler := range handlers { func() { handler(client, m) m.Ack() }() } case <-r.stop: return } } }() }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
enc.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/enc.go#L61-L73
go
train
// NewEncodedConn will wrap an existing Connection and utilize the appropriate registered // encoder.
func NewEncodedConn(c *Conn, encType string) (*EncodedConn, error)
// NewEncodedConn will wrap an existing Connection and utilize the appropriate registered // encoder. func NewEncodedConn(c *Conn, encType string) (*EncodedConn, error)
{ if c == nil { return nil, errors.New("nats: Nil Connection") } if c.IsClosed() { return nil, ErrConnectionClosed } ec := &EncodedConn{Conn: c, Enc: EncoderForType(encType)} if ec.Enc == nil { return nil, fmt.Errorf("no encoder registered for '%s'", encType) } return ec, nil }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
enc.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/enc.go#L76-L80
go
train
// RegisterEncoder will register the encType with the given Encoder. Useful for customization.
func RegisterEncoder(encType string, enc Encoder)
// RegisterEncoder will register the encType with the given Encoder. Useful for customization. func RegisterEncoder(encType string, enc Encoder)
{ encLock.Lock() defer encLock.Unlock() encMap[encType] = enc }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
enc.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/enc.go#L83-L87
go
train
// EncoderForType will return the registered Encoder for the encType.
func EncoderForType(encType string) Encoder
// EncoderForType will return the registered Encoder for the encType. func EncoderForType(encType string) Encoder
{ encLock.Lock() defer encLock.Unlock() return encMap[encType] }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
enc.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/enc.go#L91-L97
go
train
// Publish publishes the data argument to the given subject. The data argument // will be encoded using the associated encoder.
func (c *EncodedConn) Publish(subject string, v interface{}) error
// Publish publishes the data argument to the given subject. The data argument // will be encoded using the associated encoder. func (c *EncodedConn) Publish(subject string, v interface{}) error
{ b, err := c.Enc.Encode(subject, v) if err != nil { return err } return c.Conn.publish(subject, _EMPTY_, b) }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
enc.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/enc.go#L102-L108
go
train
// PublishRequest will perform a Publish() expecting a response on the // reply subject. Use Request() for automatically waiting for a response // inline.
func (c *EncodedConn) PublishRequest(subject, reply string, v interface{}) error
// PublishRequest will perform a Publish() expecting a response on the // reply subject. Use Request() for automatically waiting for a response // inline. func (c *EncodedConn) PublishRequest(subject, reply string, v interface{}) error
{ b, err := c.Enc.Encode(subject, v) if err != nil { return err } return c.Conn.publish(subject, reply, b) }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
enc.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/enc.go#L113-L129
go
train
// Request will create an Inbox and perform a Request() call // with the Inbox reply for the data v. A response will be // decoded into the vPtrResponse.
func (c *EncodedConn) Request(subject string, v interface{}, vPtr interface{}, timeout time.Duration) error
// Request will create an Inbox and perform a Request() call // with the Inbox reply for the data v. A response will be // decoded into the vPtrResponse. func (c *EncodedConn) Request(subject string, v interface{}, vPtr interface{}, timeout time.Duration) error
{ b, err := c.Enc.Encode(subject, v) if err != nil { return err } m, err := c.Conn.Request(subject, b, timeout) if err != nil { return err } if reflect.TypeOf(vPtr) == emptyMsgType { mPtr := vPtr.(*Msg) *mPtr = *m } else { err = c.Enc.Decode(m.Subject, m.Data, vPtr) } return err }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
enc.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/enc.go#L156-L166
go
train
// Dissect the cb Handler's signature
func argInfo(cb Handler) (reflect.Type, int)
// Dissect the cb Handler's signature func argInfo(cb Handler) (reflect.Type, int)
{ cbType := reflect.TypeOf(cb) if cbType.Kind() != reflect.Func { panic("nats: Handler needs to be a func") } numArgs := cbType.NumIn() if numArgs == 0 { return nil, numArgs } return cbType.In(numArgs - 1), numArgs }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
enc.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/enc.go#L173-L175
go
train
// Subscribe will create a subscription on the given subject and process incoming // messages using the specified Handler. The Handler should be a func that matches // a signature from the description of Handler from above.
func (c *EncodedConn) Subscribe(subject string, cb Handler) (*Subscription, error)
// Subscribe will create a subscription on the given subject and process incoming // messages using the specified Handler. The Handler should be a func that matches // a signature from the description of Handler from above. func (c *EncodedConn) Subscribe(subject string, cb Handler) (*Subscription, error)
{ return c.subscribe(subject, _EMPTY_, cb) }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
enc.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/enc.go#L180-L182
go
train
// QueueSubscribe will create a queue subscription on the given subject and process // incoming messages using the specified Handler. The Handler should be a func that // matches a signature from the description of Handler from above.
func (c *EncodedConn) QueueSubscribe(subject, queue string, cb Handler) (*Subscription, error)
// QueueSubscribe will create a queue subscription on the given subject and process // incoming messages using the specified Handler. The Handler should be a func that // matches a signature from the description of Handler from above. func (c *EncodedConn) QueueSubscribe(subject, queue string, cb Handler) (*Subscription, error)
{ return c.subscribe(subject, queue, cb) }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
enc.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/enc.go#L185-L238
go
train
// Internal implementation that all public functions will use.
func (c *EncodedConn) subscribe(subject, queue string, cb Handler) (*Subscription, error)
// Internal implementation that all public functions will use. func (c *EncodedConn) subscribe(subject, queue string, cb Handler) (*Subscription, error)
{ if cb == nil { return nil, errors.New("nats: Handler required for EncodedConn Subscription") } argType, numArgs := argInfo(cb) if argType == nil { return nil, errors.New("nats: Handler requires at least one argument") } cbValue := reflect.ValueOf(cb) wantsRaw := (argType == emptyMsgType) natsCB := func(m *Msg) { var oV []reflect.Value if wantsRaw { oV = []reflect.Value{reflect.ValueOf(m)} } else { var oPtr reflect.Value if argType.Kind() != reflect.Ptr { oPtr = reflect.New(argType) } else { oPtr = reflect.New(argType.Elem()) } if err := c.Enc.Decode(m.Subject, m.Data, oPtr.Interface()); err != nil { if c.Conn.Opts.AsyncErrorCB != nil { c.Conn.ach.push(func() { c.Conn.Opts.AsyncErrorCB(c.Conn, m.Sub, errors.New("nats: Got an error trying to unmarshal: "+err.Error())) }) } return } if argType.Kind() != reflect.Ptr { oPtr = reflect.Indirect(oPtr) } // Callback Arity switch numArgs { case 1: oV = []reflect.Value{oPtr} case 2: subV := reflect.ValueOf(m.Subject) oV = []reflect.Value{subV, oPtr} case 3: subV := reflect.ValueOf(m.Subject) replyV := reflect.ValueOf(m.Reply) oV = []reflect.Value{subV, replyV, oPtr} } } cbValue.Call(oV) } return c.Conn.subscribe(subject, queue, natsCB, nil, false) }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
enc.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/enc.go#L241-L243
go
train
// FlushTimeout allows a Flush operation to have an associated timeout.
func (c *EncodedConn) FlushTimeout(timeout time.Duration) (err error)
// FlushTimeout allows a Flush operation to have an associated timeout. func (c *EncodedConn) FlushTimeout(timeout time.Duration) (err error)
{ return c.Conn.FlushTimeout(timeout) }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
encoders/builtin/default_enc.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/encoders/builtin/default_enc.go#L38-L58
go
train
// Encode
func (je *DefaultEncoder) Encode(subject string, v interface{}) ([]byte, error)
// Encode func (je *DefaultEncoder) Encode(subject string, v interface{}) ([]byte, error)
{ switch arg := v.(type) { case string: bytes := *(*[]byte)(unsafe.Pointer(&arg)) return bytes, nil case []byte: return arg, nil case bool: if arg { return trueB, nil } else { return falseB, nil } case nil: return nilB, nil default: var buf bytes.Buffer fmt.Fprintf(&buf, "%+v", arg) return buf.Bytes(), nil } }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
encoders/builtin/default_enc.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/encoders/builtin/default_enc.go#L61-L117
go
train
// Decode
func (je *DefaultEncoder) Decode(subject string, data []byte, vPtr interface{}) error
// Decode func (je *DefaultEncoder) Decode(subject string, data []byte, vPtr interface{}) error
{ // Figure out what it's pointing to... sData := *(*string)(unsafe.Pointer(&data)) switch arg := vPtr.(type) { case *string: *arg = sData return nil case *[]byte: *arg = data return nil case *int: n, err := strconv.ParseInt(sData, 10, 64) if err != nil { return err } *arg = int(n) return nil case *int32: n, err := strconv.ParseInt(sData, 10, 64) if err != nil { return err } *arg = int32(n) return nil case *int64: n, err := strconv.ParseInt(sData, 10, 64) if err != nil { return err } *arg = int64(n) return nil case *float32: n, err := strconv.ParseFloat(sData, 32) if err != nil { return err } *arg = float32(n) return nil case *float64: n, err := strconv.ParseFloat(sData, 64) if err != nil { return err } *arg = float64(n) return nil case *bool: b, err := strconv.ParseBool(sData) if err != nil { return err } *arg = b return nil default: vt := reflect.TypeOf(arg).Elem() return fmt.Errorf("nats: Default Encoder can't decode to type %s", vt) } }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
parser.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/parser.go#L73-L401
go
train
// parse is the fast protocol parser engine.
func (nc *Conn) parse(buf []byte) error
// parse is the fast protocol parser engine. func (nc *Conn) parse(buf []byte) error
{ var i int var b byte // Move to loop instead of range syntax to allow jumping of i for i = 0; i < len(buf); i++ { b = buf[i] switch nc.ps.state { case OP_START: switch b { case 'M', 'm': nc.ps.state = OP_M case 'P', 'p': nc.ps.state = OP_P case '+': nc.ps.state = OP_PLUS case '-': nc.ps.state = OP_MINUS case 'I', 'i': nc.ps.state = OP_I default: goto parseErr } case OP_M: switch b { case 'S', 's': nc.ps.state = OP_MS default: goto parseErr } case OP_MS: switch b { case 'G', 'g': nc.ps.state = OP_MSG default: goto parseErr } case OP_MSG: switch b { case ' ', '\t': nc.ps.state = OP_MSG_SPC default: goto parseErr } case OP_MSG_SPC: switch b { case ' ', '\t': continue default: nc.ps.state = MSG_ARG nc.ps.as = i } case MSG_ARG: switch b { case '\r': nc.ps.drop = 1 case '\n': var arg []byte if nc.ps.argBuf != nil { arg = nc.ps.argBuf } else { arg = buf[nc.ps.as : i-nc.ps.drop] } if err := nc.processMsgArgs(arg); err != nil { return err } nc.ps.drop, nc.ps.as, nc.ps.state = 0, i+1, MSG_PAYLOAD // jump ahead with the index. If this overruns // what is left we fall out and process split // buffer. i = nc.ps.as + nc.ps.ma.size - 1 default: if nc.ps.argBuf != nil { nc.ps.argBuf = append(nc.ps.argBuf, b) } } case MSG_PAYLOAD: if nc.ps.msgBuf != nil { if len(nc.ps.msgBuf) >= nc.ps.ma.size { nc.processMsg(nc.ps.msgBuf) nc.ps.argBuf, nc.ps.msgBuf, nc.ps.state = nil, nil, MSG_END } else { // copy as much as we can to the buffer and skip ahead. toCopy := nc.ps.ma.size - len(nc.ps.msgBuf) avail := len(buf) - i if avail < toCopy { toCopy = avail } if toCopy > 0 { start := len(nc.ps.msgBuf) // This is needed for copy to work. nc.ps.msgBuf = nc.ps.msgBuf[:start+toCopy] copy(nc.ps.msgBuf[start:], buf[i:i+toCopy]) // Update our index i = (i + toCopy) - 1 } else { nc.ps.msgBuf = append(nc.ps.msgBuf, b) } } } else if i-nc.ps.as >= nc.ps.ma.size { nc.processMsg(buf[nc.ps.as:i]) nc.ps.argBuf, nc.ps.msgBuf, nc.ps.state = nil, nil, MSG_END } case MSG_END: switch b { case '\n': nc.ps.drop, nc.ps.as, nc.ps.state = 0, i+1, OP_START default: continue } case OP_PLUS: switch b { case 'O', 'o': nc.ps.state = OP_PLUS_O default: goto parseErr } case OP_PLUS_O: switch b { case 'K', 'k': nc.ps.state = OP_PLUS_OK default: goto parseErr } case OP_PLUS_OK: switch b { case '\n': nc.processOK() nc.ps.drop, nc.ps.state = 0, OP_START } case OP_MINUS: switch b { case 'E', 'e': nc.ps.state = OP_MINUS_E default: goto parseErr } case OP_MINUS_E: switch b { case 'R', 'r': nc.ps.state = OP_MINUS_ER default: goto parseErr } case OP_MINUS_ER: switch b { case 'R', 'r': nc.ps.state = OP_MINUS_ERR default: goto parseErr } case OP_MINUS_ERR: switch b { case ' ', '\t': nc.ps.state = OP_MINUS_ERR_SPC default: goto parseErr } case OP_MINUS_ERR_SPC: switch b { case ' ', '\t': continue default: nc.ps.state = MINUS_ERR_ARG nc.ps.as = i } case MINUS_ERR_ARG: switch b { case '\r': nc.ps.drop = 1 case '\n': var arg []byte if nc.ps.argBuf != nil { arg = nc.ps.argBuf nc.ps.argBuf = nil } else { arg = buf[nc.ps.as : i-nc.ps.drop] } nc.processErr(string(arg)) nc.ps.drop, nc.ps.as, nc.ps.state = 0, i+1, OP_START default: if nc.ps.argBuf != nil { nc.ps.argBuf = append(nc.ps.argBuf, b) } } case OP_P: switch b { case 'I', 'i': nc.ps.state = OP_PI case 'O', 'o': nc.ps.state = OP_PO default: goto parseErr } case OP_PO: switch b { case 'N', 'n': nc.ps.state = OP_PON default: goto parseErr } case OP_PON: switch b { case 'G', 'g': nc.ps.state = OP_PONG default: goto parseErr } case OP_PONG: switch b { case '\n': nc.processPong() nc.ps.drop, nc.ps.state = 0, OP_START } case OP_PI: switch b { case 'N', 'n': nc.ps.state = OP_PIN default: goto parseErr } case OP_PIN: switch b { case 'G', 'g': nc.ps.state = OP_PING default: goto parseErr } case OP_PING: switch b { case '\n': nc.processPing() nc.ps.drop, nc.ps.state = 0, OP_START } case OP_I: switch b { case 'N', 'n': nc.ps.state = OP_IN default: goto parseErr } case OP_IN: switch b { case 'F', 'f': nc.ps.state = OP_INF default: goto parseErr } case OP_INF: switch b { case 'O', 'o': nc.ps.state = OP_INFO default: goto parseErr } case OP_INFO: switch b { case ' ', '\t': nc.ps.state = OP_INFO_SPC default: goto parseErr } case OP_INFO_SPC: switch b { case ' ', '\t': continue default: nc.ps.state = INFO_ARG nc.ps.as = i } case INFO_ARG: switch b { case '\r': nc.ps.drop = 1 case '\n': var arg []byte if nc.ps.argBuf != nil { arg = nc.ps.argBuf nc.ps.argBuf = nil } else { arg = buf[nc.ps.as : i-nc.ps.drop] } nc.processAsyncInfo(arg) nc.ps.drop, nc.ps.as, nc.ps.state = 0, i+1, OP_START default: if nc.ps.argBuf != nil { nc.ps.argBuf = append(nc.ps.argBuf, b) } } default: goto parseErr } } // Check for split buffer scenarios if (nc.ps.state == MSG_ARG || nc.ps.state == MINUS_ERR_ARG || nc.ps.state == INFO_ARG) && nc.ps.argBuf == nil { nc.ps.argBuf = nc.ps.scratch[:0] nc.ps.argBuf = append(nc.ps.argBuf, buf[nc.ps.as:i-nc.ps.drop]...) // FIXME, check max len } // Check for split msg if nc.ps.state == MSG_PAYLOAD && nc.ps.msgBuf == nil { // We need to clone the msgArg if it is still referencing the // read buffer and we are not able to process the msg. if nc.ps.argBuf == nil { nc.cloneMsgArg() } // If we will overflow the scratch buffer, just create a // new buffer to hold the split message. if nc.ps.ma.size > cap(nc.ps.scratch)-len(nc.ps.argBuf) { lrem := len(buf[nc.ps.as:]) nc.ps.msgBuf = make([]byte, lrem, nc.ps.ma.size) copy(nc.ps.msgBuf, buf[nc.ps.as:]) } else { nc.ps.msgBuf = nc.ps.scratch[len(nc.ps.argBuf):len(nc.ps.argBuf)] nc.ps.msgBuf = append(nc.ps.msgBuf, (buf[nc.ps.as:])...) } } return nil parseErr: return fmt.Errorf("nats: Parse Error [%d]: '%s'", nc.ps.state, buf[i:]) }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
parser.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/parser.go#L405-L413
go
train
// cloneMsgArg is used when the split buffer scenario has the pubArg in the existing read buffer, but // we need to hold onto it into the next read.
func (nc *Conn) cloneMsgArg()
// cloneMsgArg is used when the split buffer scenario has the pubArg in the existing read buffer, but // we need to hold onto it into the next read. func (nc *Conn) cloneMsgArg()
{ nc.ps.argBuf = nc.ps.scratch[:0] nc.ps.argBuf = append(nc.ps.argBuf, nc.ps.ma.subject...) nc.ps.argBuf = append(nc.ps.argBuf, nc.ps.ma.reply...) nc.ps.ma.subject = nc.ps.argBuf[:len(nc.ps.ma.subject)] if nc.ps.ma.reply != nil { nc.ps.ma.reply = nc.ps.argBuf[len(nc.ps.ma.subject):] } }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
parser.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/parser.go#L470-L481
go
train
// parseInt64 expects decimal positive numbers. We // return -1 to signal error
func parseInt64(d []byte) (n int64)
// parseInt64 expects decimal positive numbers. We // return -1 to signal error func parseInt64(d []byte) (n int64)
{ if len(d) == 0 { return -1 } for _, dec := range d { if dec < ascii_0 || dec > ascii_9 { return -1 } n = n*10 + (int64(dec) - ascii_0) } return n }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L117-L129
go
train
// GetDefaultOptions returns default configuration options for the client.
func GetDefaultOptions() Options
// GetDefaultOptions returns default configuration options for the client. func GetDefaultOptions() Options
{ return Options{ AllowReconnect: true, MaxReconnect: DefaultMaxReconnect, ReconnectWait: DefaultReconnectWait, Timeout: DefaultTimeout, PingInterval: DefaultPingInterval, MaxPingsOut: DefaultMaxPingOut, SubChanLen: DefaultMaxChanLen, ReconnectBufSize: DefaultReconnectBufSize, DrainTimeout: DefaultDrainTimeout, } }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L515-L526
go
train
// Connect will attempt to connect to the NATS system. // The url can contain username/password semantics. e.g. nats://derek:pass@localhost:4222 // Comma separated arrays are also supported, e.g. urlA, urlB. // Options start with the defaults but can be overridden.
func Connect(url string, options ...Option) (*Conn, error)
// Connect will attempt to connect to the NATS system. // The url can contain username/password semantics. e.g. nats://derek:pass@localhost:4222 // Comma separated arrays are also supported, e.g. urlA, urlB. // Options start with the defaults but can be overridden. func Connect(url string, options ...Option) (*Conn, error)
{ opts := GetDefaultOptions() opts.Servers = processUrlString(url) for _, opt := range options { if opt != nil { if err := opt(&opts); err != nil { return nil, err } } } return opts.Connect() }
nats-io/go-nats
36d30b0ba7aa260ae25b4f3d312b2a700106fd78
nats.go
https://github.com/nats-io/go-nats/blob/36d30b0ba7aa260ae25b4f3d312b2a700106fd78/nats.go#L531-L536
go
train
// Options that can be passed to Connect. // Name is an Option to set the client name.
func Name(name string) Option
// Options that can be passed to Connect. // Name is an Option to set the client name. func Name(name string) Option
{ return func(o *Options) error { o.Name = name return nil } }