From 390c4eceda3f8e99bf1b73551a994fcc4e75e634 Mon Sep 17 00:00:00 2001 From: Evan Chen Date: Sat, 16 Oct 2021 22:40:23 +0800 Subject: [PATCH] feat: #3 --- cmd/server.go | 43 ++++++++++++++++++++++++++----------------- 1 file changed, 26 insertions(+), 17 deletions(-) diff --git a/cmd/server.go b/cmd/server.go index 3d1bdc9..62e81a5 100644 --- a/cmd/server.go +++ b/cmd/server.go @@ -5,6 +5,7 @@ import ( "log" "net" "net/http" + "time" "github.com/spf13/cobra" ) @@ -31,19 +32,16 @@ func init() { func StartServer() error { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - ip := r.Header.Get("X-Real-Ip") - if ip == "" { - ip = r.Header.Get("X-Forwarded-For") - } - if ip == "" { - var err error - ip, _, err = net.SplitHostPort(r.RemoteAddr) - if err != nil { - ip = r.RemoteAddr - } - } - r.Header.Add("X-Myip", ip) + ip := GetIP(r) fmt.Fprint(w, ip+"\n") + + // logging + user := r.URL.Query().Get("name") + if user == "" { + user = r.URL.String() + } + host, _, _ := net.SplitHostPort(r.RemoteAddr) + log.Printf("%s %s %s %s %s\n", time.Now().Format("2006-01-02-15:04:05"), host, ip, user, r.Header.Get("User-Agent")) }) err := http.ListenAndServe(addr+":"+port, simpleLogger(http.DefaultServeMux)) @@ -54,6 +52,21 @@ func StartServer() error { return nil } +func GetIP(r *http.Request) string { + ip := r.Header.Get("X-Real-Ip") + if ip == "" { + ip = r.Header.Get("X-Forwarded-For") + } + if ip == "" { + var err error + ip, _, err = net.SplitHostPort(r.RemoteAddr) + if err != nil { + ip = r.RemoteAddr + } + } + return ip +} + func simpleLogger(handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -63,11 +76,7 @@ func simpleLogger(handler http.Handler) http.Handler { // fmt.Println(name, value) // } // } - user := r.URL.Query().Get("name") - if user == "" { - user = r.URL.String() - } - log.Printf("%s %s %s %s\n", r.RemoteAddr, r.Method, user, r.Header.Get("User-Agent")) + // log.Printf("%s %s %s %s\n", r.RemoteAddr, r.Method, r.URL, r.Header.Get("User-Agent")) handler.ServeHTTP(w, r) }) }