github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/integration/messagebus/glue/sample/Channels/main.go (about) 1 /* 2 * Glue - Robust Go and Javascript Socket Library 3 * Copyright (C) 2015 Roland Singer <roland.singer[at]desertbit.com> 4 * 5 * This program is free software: you can redistribute it and/or modify 6 * it under the terms of the GNU General Public License as published by 7 * the Free Software Foundation, either version 3 of the License, or 8 * (at your option) any later version. 9 * 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * 15 * You should have received a copy of the GNU General Public License 16 * along with this program. If not, see <http://www.gnu.org/licenses/>. 17 */ 18 19 package main 20 21 import ( 22 "log" 23 "net/http" 24 25 "github.com/desertbit/glue" 26 ) 27 28 func main() { 29 // Set the http file server. 30 http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("public")))) 31 http.Handle("/dist/", http.StripPrefix("/dist/", http.FileServer(http.Dir("../../client/dist")))) 32 33 // Create a new glue server. 34 server := glue.NewServer(glue.Options{ 35 HTTPListenAddress: ":8080", 36 }) 37 38 // Release the glue server on defer. 39 // This will block new incoming connections 40 // and close all current active sockets. 41 defer server.Release() 42 43 // Set the glue event function to handle new incoming socket connections. 44 server.OnNewSocket(onNewSocket) 45 46 // Run the glue server. 47 err := server.Run() 48 if err != nil { 49 log.Fatalf("Glue Run: %v", err) 50 } 51 } 52 53 func onNewSocket(s *glue.Socket) { 54 // We won't read any data from the socket itself. 55 // Discard received data! 56 s.DiscardRead() 57 58 // Set a function which is triggered as soon as the socket is closed. 59 s.OnClose(func() { 60 log.Printf("socket closed with remote address: %s", s.RemoteAddr()) 61 }) 62 63 // Create a channel. 64 c := s.Channel("golang") 65 66 // Set the channel on read event function. 67 c.OnRead(func(data string) { 68 // Echo the received data back to the client. 69 c.Write("channel golang: " + data) 70 }) 71 72 // Write to the channel. 73 c.Write("Hello Gophers!") 74 }