2 Commits

Author SHA1 Message Date
4a4db8d195 added JSON API on /api 2015-11-09 22:33:16 +01:00
139ff4dadd websocket support /echo 2015-10-14 22:58:01 +02:00

82
app.go
View File

@ -1,28 +1,70 @@
package main package main
import ( import (
"encoding/json"
"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)
http.HandleFunc("/api", api)
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
for _, i := range ifaces { for _, i := range ifaces {
addrs, _ := i.Addrs() addrs, _ := i.Addrs()
// handle err // handle err
@ -39,3 +81,31 @@ func whoamI(w http.ResponseWriter, req *http.Request) {
} }
req.Write(w) req.Write(w)
} }
func api(w http.ResponseWriter, req *http.Request) {
hostname, _ := os.Hostname()
data := struct {
Hostname string `json:"hostname,omitempty"`
IP []string `json:"ip,omitempty"`
}{
hostname,
[]string{},
}
ifaces, _ := net.Interfaces()
for _, i := range ifaces {
addrs, _ := i.Addrs()
// handle err
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
data.IP = append(data.IP, ip.String())
}
}
json.NewEncoder(w).Encode(data)
}