nanomsg.org/go/mangos/v2@v2.0.9-0.20200203084354-8a092611e461/examples/websocket/main.go (about) 1 // Copyright 2016 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 // websocket implements a simple websocket server for mangos, demonstrating 16 // how to use multiplex multiple sockets on a single HTTP server instance. 17 // 18 // The server listens, and offers three paths: 19 // 20 // - sub/ - SUB socket, publishes a message "PUB <count> <time>" each second 21 // - req/ - REQ socket, responds with a reply "REPLY <count> <time>" 22 // - static/ - static content, provided as ASCII "STATIC" 23 // 24 // To use: 25 // 26 // $ go build . 27 // $ port=40899 28 // $ ./websocket server port & pid=$! && sleep 1 29 // $ ./websocket req $port 30 // $ ./websocket sub $port 31 // $ ./websocket static $port 32 // $ kill $pid 33 // 34 package main 35 36 import ( 37 "fmt" 38 "io/ioutil" 39 "net/http" 40 "os" 41 "strconv" 42 ) 43 44 func die(format string, v ...interface{}) { 45 fmt.Fprintln(os.Stderr, fmt.Sprintf(format, v...)) 46 os.Exit(1) 47 } 48 49 func usage() { 50 die("Usage: %s <server|req|sub|static> <port>\n", os.Args[0]) 51 } 52 53 func main() { 54 55 if len(os.Args) != 3 { 56 usage() 57 } 58 port, e := strconv.Atoi(os.Args[2]) 59 if e != nil || port < 0 || port > 65535 { 60 die("Invalid port number") 61 } 62 switch os.Args[1] { 63 case "server": 64 server(port) 65 case "req": 66 reqClient(port) 67 case "sub": 68 subClient(port) 69 case "static": 70 staticClient(port) 71 default: 72 usage() 73 } 74 os.Exit(0) 75 } 76 77 func server(port int) { 78 mux := http.NewServeMux() 79 80 addStaticHandler(mux) 81 addSubHandler(mux, port) 82 addReqHandler(mux, port) 83 84 e := http.ListenAndServe(fmt.Sprintf(":%d", port), mux) 85 die("Http server died: %v", e) 86 } 87 88 func staticClient(port int) { 89 url := fmt.Sprintf("http://127.0.0.1:%d/static", port) 90 resp, err := http.Get(url) 91 if err != nil { 92 die("Get failed: %v", err) 93 } 94 if resp.StatusCode != 200 { 95 die("Status code %d", resp.StatusCode) 96 } 97 body, _ := ioutil.ReadAll(resp.Body) 98 fmt.Printf("%s\n", string(body)) 99 os.Exit(0) 100 }