feat: #3
parent
abe243e815
commit
390c4eceda
|
@ -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)
|
||||
})
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue