github.com/gdamore/mangos@v1.4.0/examples/websocket/reqhandler.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/rep" 24 "nanomsg.org/go-mangos/transport/ws" 25 ) 26 27 // reqHandler just spins on the socket and reads messages. It replies 28 // with "REPLY <time>". Not very interesting... 29 30 func reqHandler(sock mangos.Socket) { 31 count := 0 32 for { 33 // don't care about the content of received message 34 _, e := sock.Recv() 35 if e != nil { 36 die("Cannot get request: %v", e) 37 } 38 reply := fmt.Sprintf("REPLY #%d %s", count, time.Now().String()) 39 if e := sock.Send([]byte(reply)); e != nil { 40 die("Cannot send reply: %v", e) 41 } 42 count++ 43 } 44 } 45 46 func addReqHandler(mux *http.ServeMux, port int) { 47 sock, _ := rep.NewSocket() 48 49 sock.AddTransport(ws.NewTransport()) 50 51 url := fmt.Sprintf("ws://127.0.0.1:%d/req", port) 52 53 if l, e := sock.NewListener(url, nil); e != nil { 54 die("bad listener: %v", e) 55 } else if h, e := l.GetOption(ws.OptionWebSocketHandler); e != nil { 56 die("bad handler: %v", e) 57 } else { 58 mux.Handle("/req", h.(http.Handler)) 59 l.Listen() 60 } 61 go reqHandler(sock) 62 }