Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Intercept messages from published #29

Closed
darlandieterich opened this issue Nov 12, 2020 · 6 comments
Closed

Intercept messages from published #29

darlandieterich opened this issue Nov 12, 2020 · 6 comments

Comments

@darlandieterich
Copy link

How intercept messages from published?

My init code:

package main

import (
	"context"
	"net"
	"os"
	"os/signal"
	"syscall"
	"log"
	"github.com/DrmagicE/gmqtt"
)
func main() {
	// listener
	ln, err := net.Listen("tcp", ":1883")
	if err != nil {
		log.Fatalln(err.Error())
		return
	}

	s := gmqtt.NewServer(
		gmqtt.WithTCPListener(ln),
	)

	s.Run()
	signalCh := make(chan os.Signal, 1)
	signal.Notify(signalCh, os.Interrupt, syscall.SIGTERM)
	<-signalCh
	s.Stop(context.Background())
}
@DrmagicE
Copy link
Owner

DrmagicE commented Nov 12, 2020

You can either use the OnMsgArrived hook or implement a plugin.Here is some examples:

  1. Using hook: https://github.com/DrmagicE/gmqtt/blob/v0.1.3/examples/hook/main.go#L76
  2. Using plugin: Modify message before delivering to client #24 (comment)

@darlandieterich
Copy link
Author

Hi!
Ok, then, how intercept the message in string?

OnMsgArrived: func(ctx context.Context, client gmqtt.Client, msg packets.Message) (valid bool) {
        fmt.Println(msg) ///&{false 0 false /test/hello 0 [116 101 115 116 97 110 100 111 111 111 32 111 117 116 114 111 32 118 97 108 111 114 32 49 52 58 48 57 58 52 57 40 53 57 57 41]}
	fmt.Println("Topic", msg.Topic)
	fmt.Println("Payload", msg.Payload)

	//Only qos1 & qos0 are acceptable(will be delivered)
	if msg.Qos() == packets.QOS_2 {
		return false
	}
	return true
},

tnks

@DrmagicE
Copy link
Owner

fmt.Println("Payload", string(msg.Payload))

@darlandieterich
Copy link
Author

well, I tried this before, but show error on compile:
cannot convert msg.Payload (type func() []byte) to type string

@DrmagicE
Copy link
Owner

Oh, my fault.. Payload is a function .Try fmt.Println("Payload", string(msg.Payload())) @darlandieterich

@darlandieterich
Copy link
Author

now this run so charm 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants