pull/6/head
Evan Chen 2021-10-16 22:40:23 +08:00
parent c81cbffbe1
commit 8aa35a546f
1 changed files with 26 additions and 17 deletions

View File

@ -5,6 +5,7 @@ import (
"log" "log"
"net" "net"
"net/http" "net/http"
"time"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -31,19 +32,16 @@ func init() {
func StartServer() error { func StartServer() error {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
ip := r.Header.Get("X-Real-Ip") ip := GetIP(r)
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)
fmt.Fprint(w, ip+"\n") 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)) err := http.ListenAndServe(addr+":"+port, simpleLogger(http.DefaultServeMux))
@ -54,6 +52,21 @@ func StartServer() error {
return nil 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 { func simpleLogger(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 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) // fmt.Println(name, value)
// } // }
// } // }
user := r.URL.Query().Get("name") // log.Printf("%s %s %s %s\n", r.RemoteAddr, r.Method, r.URL, r.Header.Get("User-Agent"))
if user == "" {
user = r.URL.String()
}
log.Printf("%s %s %s %s\n", r.RemoteAddr, r.Method, user, r.Header.Get("User-Agent"))
handler.ServeHTTP(w, r) handler.ServeHTTP(w, r)
}) })
} }