Fiber: 馃悰 ctx.IPs() returns wrong result when there is no X-Forwarded-For in request header

Created on 24 Jul 2020  路  4Comments  路  Source: gofiber/fiber

Fiber version
v1.13.3

Issue description
fiber.Ctx.IPs() returns slice of string with one empty string ([]string{""}) in it when there is no X-Forwarded-For header. But what I espect is an empty slice of string. I think it's cased by a recent change in #612

https://github.com/gofiber/fiber/pull/612/files#diff-8500aba9f2dd08390bcbe6a506b66564R501

ips = make([]string, bytes.Count(header, []byte(","))+1)

In line L501. I think it's not a good idea to calculate the forward ips' length by the counting the comma becase there could be no X-Forwarded-For field in header.

BTW, should we consider the non-standard HTTP headers? For example in the X-Forwarded-For header:

a,b,  c # no space or extra space after comma
,a,b    # comma in wrong place
a,,b    # and this
,       # only comma

What should IPs() return? I assume []string{a,b,c} []string{a,b} []string{a,b} []string{} is what we expected, right?

鈽笍 Bug 馃洜 In Progress

Most helpful comment

Thanks for your reporting! If the value of X-Forwarded-For header is empty, the answer should be an empty slice too(or nil).

And we don鈥檛 consider non-standard Http headers until now.

All 4 comments

Thanks for opening your first issue here! 馃帀 Be sure to follow the issue template! If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

What about switching back to the strings.Split way, with some improvement:

func (ctx *Ctx) IPs() []string {
    ips := []string{}
    for _, ip := range strings.Split(ctx.Get(HeaderXForwardedFor), ",") {
        trimmedIP := strings.TrimSpace(ip)
        if len(trimmedIP) != 0 {
            ips = append(ips, trimmedIP)
        }
    }
    return ips
}

In most cases, there could be only one ip or empty in the X-Forwarded-For header. I think this part is only slight impact on performance 馃

Thanks for your reporting! If the value of X-Forwarded-For header is empty, the answer should be an empty slice too(or nil).

And we don鈥檛 consider non-standard Http headers until now.

@abowloflrf, nice find 馃憤 should be tagged next week

Was this page helpful?
0 / 5 - 0 ratings