forked from jwilder/whoami
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathhttp.go
108 lines (90 loc) · 2.08 KB
/
http.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"net"
"net/http"
"net/url"
"os"
"runtime"
"time"
viper "github.com/spf13/viper"
logrus "gopkg.in/sirupsen/logrus.v1"
)
type DataResponse struct {
Hostname string `json:"hostname,omitempty"`
Platform string `json:"platform,omitempty"`
IP []string `json:"ip,omitempty"`
Headers http.Header `json:"header,omitempty"`
Environment []string `json:"env,omitempty"`
}
var port string
func init() {
flag.StringVar(&port, "port", "8080", "give me a port number")
lvl, err := logrus.ParseLevel(viper.GetString("loglevel"))
if err != nil {
lvl = logrus.WarnLevel
}
logrus.SetLevel(lvl)
}
func main() {
flag.Parse()
http.HandleFunc("/", index)
http.HandleFunc("/api", api)
log.Println("Starting up on port " + port)
if err := http.ListenAndServe(":"+port, nil); err != nil {
http.ListenAndServe(":"+port, nil)
}
}
func index(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)
}
}
data := fetchData(req)
fmt.Fprintf(os.Stdout, "I'm %s\n", data.Hostname)
fmt.Fprintf(w, "I'm %s running on %s\n\n", data.Hostname, data.Platform)
for _, ip := range data.IP {
fmt.Fprintln(w, "IP:", ip)
}
for _, env := range data.Environment {
fmt.Fprintln(w, "ENV:", env)
}
req.Write(w)
}
func api(w http.ResponseWriter, req *http.Request) {
data := fetchData(req)
json.NewEncoder(w).Encode(data)
}
func fetchData(req *http.Request) DataResponse {
hostname, _ := os.Hostname()
data := DataResponse{
hostname,
fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH),
[]string{},
req.Header,
os.Environ(),
}
ifaces, _ := net.Interfaces()
for _, i := range ifaces {
addrs, _ := i.Addrs()
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())
}
}
return data
}