websocket support /echo
This commit is contained in:
51
app.go
51
app.go
@ -2,23 +2,64 @@ package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/gorilla/websocket"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var upgrader = websocket.Upgrader{
|
||||
ReadBufferSize: 1024,
|
||||
WriteBufferSize: 1024,
|
||||
}
|
||||
|
||||
r := mux.NewRouter()
|
||||
r.HandleFunc("/", whoamI)
|
||||
http.Handle("/", r)
|
||||
func main() {
|
||||
http.HandleFunc("/echo", echoHandler)
|
||||
http.HandleFunc("/", whoamI)
|
||||
fmt.Println("Starting up on 80")
|
||||
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) {
|
||||
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()
|
||||
fmt.Fprintln(w, "Hostname:", hostname)
|
||||
ifaces, _ := net.Interfaces()
|
||||
|
Reference in New Issue
Block a user