mochi-mqtt / server

The fully compliant, embeddable high-performance Go MQTT v5 server for IoT, smarthome, and pubsub
MIT License
1.29k stars 222 forks source link

Add MQTT websocket to a custom HTTP server #345

Closed badlee closed 11 months ago

badlee commented 11 months ago

Add MQTT websocket to a custom HTTP server

func main() {
        router := gin.Default()
    ginServer := &http.Server{
        Addr:    ":13000",
        Handler: router,
                 ReadTimeout:    10 * time.Second,
        WriteTimeout:   10 * time.Second,
        MaxHeaderBytes: 1 << 20,
    }
        server := mqtt.New(nil)
    _ = server.AddHook(new(auth.AllowHook), nil)
    ws := listeners.WebsocketFromHTTPServer("websocket", ginServer)
    if err := server.AddListener(ws); err != nil {
        log.Error(err.Error())
    }
    go func() {
        err := server.Serve()
        if err != nil {
            log.Error(err.Error())
        }
    }()
    router.GET("/socket", func(c *gin.Context) {
        ws.Handler(c.Writer, c.Request)
    })
    ginServer.ListenAndServe()
}