github.com/gdamore/mangos@v1.4.0/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 "nanomsg.org/go-mangos" 23 "nanomsg.org/go-mangos/protocol/pub" 24 "nanomsg.org/go-mangos/transport/ws" 25 ) 26 27 // subHandler just spins on the socket and publishes messages. It sends 28 // "PUB #<count> <time>". Not very interesting... 29 30 func subHandler(sock mangos.Socket) { 31 count := 0 32 for { 33 msg := fmt.Sprintf("PUB #%d %s", count, time.Now().String()) 34 if e := sock.Send([]byte(msg)); e != nil { 35 die("Cannot send pub: %v", e) 36 } 37 time.Sleep(5 * time.Second) 38 count++ 39 } 40 } 41 42 func addSubHandler(mux *http.ServeMux, port int) { 43 sock, _ := pub.NewSocket() 44 45 sock.AddTransport(ws.NewTransport()) 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:", e) 53 } else { 54 mux.Handle("/sub", h.(http.Handler)) 55 l.Listen() 56 } 57 58 go subHandler(sock) 59 }