go.nanomsg.org/mangos/v3@v3.4.3-0.20240217232803-46464076f1f5/examples/websocket/subhandler.go (about) 1 // Copyright 2018 The Mangos Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use file except in compliance with the License. 5 // You may obtain a copy of the license at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package main 16 17 import ( 18 "fmt" 19 "net/http" 20 "time" 21 22 "go.nanomsg.org/mangos/v3" 23 "go.nanomsg.org/mangos/v3/protocol/pub" 24 25 // register ws transport 26 "go.nanomsg.org/mangos/v3/transport/ws" 27 ) 28 29 // subHandler just spins on the socket and publishes messages. It sends 30 // "PUB #<count> <time>". Not very interesting... 31 32 func subHandler(sock mangos.Socket) { 33 count := 0 34 for { 35 msg := fmt.Sprintf("PUB #%d %s", count, time.Now().String()) 36 if e := sock.Send([]byte(msg)); e != nil { 37 die("Cannot send pub: %v", e) 38 } 39 time.Sleep(5 * time.Second) 40 count++ 41 } 42 } 43 44 func addSubHandler(mux *http.ServeMux, port int) { 45 sock, _ := pub.NewSocket() 46 47 url := fmt.Sprintf("ws://127.0.0.1:%d/sub", port) 48 49 if l, e := sock.NewListener(url, nil); e != nil { 50 die("bad listener: %v", e) 51 } else if h, e := l.GetOption(ws.OptionWebSocketHandler); e != nil { 52 die("cannot get handler: %v", e) 53 } else { 54 mux.Handle("/sub", h.(http.Handler)) 55 l.Listen() 56 } 57 58 go subHandler(sock) 59 }