Moved determining real IP address to its own function

This commit is contained in:
Seednode 2022-12-20 18:17:33 -06:00
parent af9def38ba
commit cf79bc1d3d
2 changed files with 24 additions and 13 deletions

View File

@ -10,7 +10,7 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
var Version = "0.28.1" var Version = "0.28.2"
func init() { func init() {
rootCmd.AddCommand(versionCmd) rootCmd.AddCommand(versionCmd)

View File

@ -206,6 +206,28 @@ func refererToUri(referer string) string {
return "/" + parts[3] return "/" + parts[3]
} }
func getRealIp(r *http.Request) string {
remoteAddr := strings.SplitAfter(r.RemoteAddr, ":")
if len(remoteAddr) <= 0 {
return r.RemoteAddr
}
remotePort := remoteAddr[len(remoteAddr)-1]
cfIP := r.Header.Get("Cf-Connecting-Ip")
xRealIp := r.Header.Get("X-Real-Ip")
switch {
case cfIP != "":
return cfIP + ":" + remotePort
case xRealIp != "":
return xRealIp + ":" + remotePort
default:
return r.RemoteAddr
}
}
func serveHtml(w http.ResponseWriter, r *http.Request, filePath string, dimensions *Dimensions, filters *Filters) error { func serveHtml(w http.ResponseWriter, r *http.Request, filePath string, dimensions *Dimensions, filters *Filters) error {
fileName := filepath.Base(filePath) fileName := filepath.Base(filePath)
@ -293,22 +315,11 @@ func serveStaticFile(w http.ResponseWriter, r *http.Request, paths []string) err
w.Write(buf) w.Write(buf)
if Verbose { if Verbose {
remoteAddr := ""
cfIP := r.Header.Get("Cf-Connecting-Ip")
xRealIp := r.Header.Get("X-Real-Ip")
if cfIP != "" {
remoteAddr = cfIP
} else if xRealIp != "" {
remoteAddr = xRealIp
} else {
remoteAddr = r.RemoteAddr
}
fmt.Printf("%v | Served %v (%v) to %v in %v\n", fmt.Printf("%v | Served %v (%v) to %v in %v\n",
startTime.Format(LogDate), startTime.Format(LogDate),
filePath, filePath,
humanReadableSize(len(buf)), humanReadableSize(len(buf)),
remoteAddr, getRealIp(r),
time.Since(startTime).Round(time.Microsecond), time.Since(startTime).Round(time.Microsecond),
) )
} }