Skip to content

Commit

Permalink
Implement offered comment
Browse files Browse the repository at this point in the history
  • Loading branch information
LaurenceJJones committed Jan 29, 2024
1 parent 6134b06 commit 148c725
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 13 deletions.
2 changes: 1 addition & 1 deletion config/config.go
Expand Up @@ -40,7 +40,7 @@ type Configuration struct {
AllowHeaders []string
}

TrustedProxies []string
TrustXRealIP bool `default:"false"`
}
Database struct {
Dialect string `default:"sqlite3"`
Expand Down
37 changes: 25 additions & 12 deletions router/router.go
Expand Up @@ -28,18 +28,7 @@ import (
func Create(db *database.GormDatabase, vInfo *model.VersionInfo, conf *config.Configuration) (*gin.Engine, func()) {
g := gin.New()

if conf.Server.TrustedProxies != nil {
g.SetTrustedProxies(conf.Server.TrustedProxies)
g.ForwardedByClientIP = true
}

g.Use(func(ctx *gin.Context) {
if localAddr, ok := ctx.Request.Context().Value(http.LocalAddrContextKey).(net.Addr); ok && localAddr.Network() == "unix" {
ctx.Request.RemoteAddr = "127.0.0.1:65535" // set remote address to localhost for unix socket requests
}
})

g.Use(gin.LoggerWithFormatter(logFormatter), gin.Recovery(), gerror.Handler(), location.Default())
g.Use(gin.LoggerWithFormatter(useXRealIP(conf.Server.TrustXRealIP, logFormatter)), gin.Recovery(), gerror.Handler(), location.Default())
g.NoRoute(gerror.NotFound())

if conf.Server.SSL.Enabled != nil && conf.Server.SSL.RedirectToHTTPS != nil && *conf.Server.SSL.Enabled && *conf.Server.SSL.RedirectToHTTPS {
Expand Down Expand Up @@ -259,3 +248,27 @@ func (fs *onlyImageFS) Open(name string) (http.File, error) {
}
return fs.inner.Open(name)
}

func useXRealIP(trustedProxy bool, inner gin.LogFormatter) gin.LogFormatter {
return func(params gin.LogFormatterParams) string {
params.ClientIP = getClientIp(trustedProxy, params.Request)
return inner(params)
}
}

func getClientIp(trustedProxy bool, req *http.Request) string {

Check failure on line 259 in router/router.go

View workflow job for this annotation

GitHub Actions / gotify

ST1003: func getClientIp should be getClientIP (stylecheck)
if trustedProxy {
realIpParts := strings.SplitN(req.Header.Get("x-real-ip"), ",", 2)

Check failure on line 261 in router/router.go

View workflow job for this annotation

GitHub Actions / gotify

ST1003: var realIpParts should be realIPParts (stylecheck)
if ip := strings.TrimSpace(realIpParts[0]); ip != "" {
return ip
}
}

addr := req.RemoteAddr
if addr == "@" {
return "socket"
} else if host, _, err := net.SplitHostPort(addr); err == nil {
return host
}
return addr
}

0 comments on commit 148c725

Please sign in to comment.