websocket support /echo

This commit is contained in:
emile
2015-10-14 22:58:01 +02:00
parent 64ddc0a510
commit 139ff4dadd

55
app.go
View File

@ -2,25 +2,66 @@ package main
import ( import (
"fmt" "fmt"
"github.com/gorilla/mux" "github.com/gorilla/websocket"
"log" "log"
"net" "net"
"net/http" "net/http"
"net/url"
"os" "os"
"time"
) )
func main() { var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
r := mux.NewRouter() func main() {
r.HandleFunc("/", whoamI) http.HandleFunc("/echo", echoHandler)
http.Handle("/", r) http.HandleFunc("/", whoamI)
fmt.Println("Starting up on 80") fmt.Println("Starting up on 80")
log.Fatal(http.ListenAndServe(":80", nil)) log.Fatal(http.ListenAndServe(":80", nil))
} }
func print_binary(s []byte) {
fmt.Printf("Received b:")
for n := 0; n < len(s); n++ {
fmt.Printf("%d,", s[n])
}
fmt.Printf("\n")
}
func echoHandler(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
for {
messageType, p, err := conn.ReadMessage()
if err != nil {
return
}
print_binary(p)
err = conn.WriteMessage(messageType, p)
if err != nil {
return
}
}
}
func whoamI(w http.ResponseWriter, req *http.Request) { func whoamI(w http.ResponseWriter, req *http.Request) {
u, _ := url.Parse(req.URL.String())
queryParams := u.Query()
wait := queryParams.Get("wait")
if len(wait) > 0 {
duration, err := time.ParseDuration(wait)
if err == nil {
time.Sleep(duration)
}
}
hostname, _ := os.Hostname() hostname, _ := os.Hostname()
fmt.Fprintln(w, "Hostname : ", hostname) fmt.Fprintln(w, "Hostname:", hostname)
ifaces, _ := net.Interfaces() ifaces, _ := net.Interfaces()
// handle err // handle err
for _, i := range ifaces { for _, i := range ifaces {
@ -34,7 +75,7 @@ func whoamI(w http.ResponseWriter, req *http.Request) {
case *net.IPAddr: case *net.IPAddr:
ip = v.IP ip = v.IP
} }
fmt.Fprintln(w, "IP : ", ip) fmt.Fprintln(w, "IP:", ip)
} }
} }
req.Write(w) req.Write(w)