echoip/ifconfig.go

98 lines
2.4 KiB
Go
Raw Normal View History

2012-11-19 19:12:59 +01:00
package main
import (
2012-11-25 22:41:27 +01:00
"encoding/json"
2012-11-19 19:12:59 +01:00
"fmt"
"html/template"
2012-11-19 19:12:59 +01:00
"io"
"log"
"net"
"net/http"
"regexp"
2012-11-25 13:30:39 +01:00
"strings"
2012-11-19 19:12:59 +01:00
)
type Client struct {
2012-11-25 14:43:17 +01:00
IP net.IP
2012-11-25 22:41:27 +01:00
JSON string
2012-11-25 13:30:39 +01:00
Header http.Header
}
2012-11-19 19:12:59 +01:00
func isCli(userAgent string) bool {
match, _ := regexp.MatchString("^(?i)(curl|wget|fetch\\slibfetch)\\/.*$",
userAgent)
return match
}
2012-11-25 21:25:32 +01:00
func parseRealIP(req *http.Request) net.IP {
2012-11-19 23:45:51 +01:00
var host string
realIP := req.Header.Get("X-Real-IP")
if realIP != "" {
host = realIP
} else {
2012-11-25 21:25:32 +01:00
host, _, _ = net.SplitHostPort(req.RemoteAddr)
2012-11-19 23:45:51 +01:00
}
2012-11-25 21:25:32 +01:00
return net.ParseIP(host)
2012-11-25 13:30:39 +01:00
}
func pathToKey(path string) string {
re := regexp.MustCompile("^\\/|\\.json$")
return re.ReplaceAllLiteralString(strings.ToLower(path), "")
}
func isJson(req *http.Request) bool {
return strings.HasSuffix(req.URL.Path, ".json") ||
strings.Contains(req.Header.Get("Accept"), "application/json")
}
func handler(w http.ResponseWriter, req *http.Request) {
if req.Method != "GET" {
http.Error(w, "Invalid request method", 405)
2012-11-19 19:12:59 +01:00
return
}
2012-11-25 21:25:32 +01:00
ip := parseRealIP(req)
2012-11-25 13:30:39 +01:00
header := pathToKey(req.URL.Path)
2012-11-25 22:41:27 +01:00
if isJson(req) {
if header == "all" {
b, _ := json.MarshalIndent(req.Header, "", " ")
io.WriteString(w, fmt.Sprintf("%s\n", b))
} else {
m := map[string]string{
header: req.Header.Get(header),
}
b, _ := json.MarshalIndent(m, "", " ")
io.WriteString(w, fmt.Sprintf("%s\n", b))
}
} else if isCli(req.UserAgent()) {
2012-11-25 13:30:39 +01:00
if header == "" || header == "ip" {
io.WriteString(w, fmt.Sprintf("%s\n", ip))
} else {
value := req.Header.Get(header)
io.WriteString(w, fmt.Sprintf("%s\n", value))
}
2012-11-19 19:12:59 +01:00
} else {
2012-11-25 14:43:17 +01:00
funcMap := template.FuncMap{
2012-11-25 13:30:39 +01:00
"ToLower": strings.ToLower,
}
t, _ := template.
New("index.html").
Funcs(funcMap).
ParseFiles("index.html")
2012-11-25 22:41:27 +01:00
b, _ := json.MarshalIndent(req.Header, "", " ")
client := &Client{IP: ip, JSON: string(b), Header: req.Header}
t.Execute(w, client)
2012-11-19 19:12:59 +01:00
}
}
func main() {
2012-11-21 22:52:51 +01:00
http.Handle("/assets/", http.StripPrefix("/assets/",
http.FileServer(http.Dir("assets/"))))
2012-11-19 19:12:59 +01:00
http.HandleFunc("/", handler)
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}