added JSON API on /api

This commit is contained in:
emile
2015-11-09 22:33:16 +01:00
parent 139ff4dadd
commit 4a4db8d195

31
app.go
View File

@ -1,6 +1,7 @@
package main package main
import ( import (
"encoding/json"
"fmt" "fmt"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
"log" "log"
@ -19,6 +20,7 @@ var upgrader = websocket.Upgrader{
func main() { func main() {
http.HandleFunc("/echo", echoHandler) http.HandleFunc("/echo", echoHandler)
http.HandleFunc("/", whoamI) 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))
} }
@ -63,7 +65,6 @@ func whoamI(w http.ResponseWriter, req *http.Request) {
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
@ -80,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)
}