nanomsg.org/go/mangos/v2@v2.0.9-0.20200203084354-8a092611e461/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/v2"
    23  	"nanomsg.org/go/mangos/v2/protocol/rep"
    24  
    25  	// register ws transport
    26  	"nanomsg.org/go/mangos/v2/transport/ws"
    27  )
    28  
    29  // reqHandler just spins on the socket and reads messages.  It replies
    30  // with "REPLY <time>".  Not very interesting...
    31  
    32  func reqHandler(sock mangos.Socket) {
    33  	count := 0
    34  	for {
    35  		// don't care about the content of received message
    36  		_, e := sock.Recv()
    37  		if e != nil {
    38  			die("Cannot get request: %v", e)
    39  		}
    40  		reply := fmt.Sprintf("REPLY #%d %s", count, time.Now().String())
    41  		if e := sock.Send([]byte(reply)); e != nil {
    42  			die("Cannot send reply: %v", e)
    43  		}
    44  		count++
    45  	}
    46  }
    47  
    48  func addReqHandler(mux *http.ServeMux, port int) {
    49  	sock, _ := rep.NewSocket()
    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  }