Skip to content

Commit

Permalink
fix: x-forwarded-for header
Browse files Browse the repository at this point in the history
  • Loading branch information
zhangxu19830126 committed Mar 23, 2019
1 parent 380e544 commit bc62910
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
5 changes: 5 additions & 0 deletions cmd/backend/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ func main() {
return c.String(http.StatusOK, "OK")
})

server.GET("/header", func(c echo.Context) error {
name := c.QueryParam("name")
return c.String(http.StatusOK, c.Request().Header.Get(name))
})

server.GET("/error", func(c echo.Context) error {
return c.NoContent(http.StatusBadRequest)
})
Expand Down
20 changes: 19 additions & 1 deletion pkg/proxy/filter_xforwardfor.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
package proxy

import (
"bytes"

"github.com/fagongzi/gateway/pkg/filter"
"github.com/fagongzi/util/hack"
)

var (
headerName = []byte("X-Forwarded-For")
)

// XForwardForFilter XForwardForFilter
Expand All @@ -25,6 +32,17 @@ func (f *XForwardForFilter) Name() string {

// Pre execute before proxy
func (f *XForwardForFilter) Pre(c filter.Context) (statusCode int, err error) {
c.ForwardRequest().Header.Add("X-Forwarded-For", c.OriginRequest().RemoteIP().String())
prevForward := c.OriginRequest().Request.Header.PeekBytes(headerName)
if len(prevForward) == 0 {
c.ForwardRequest().Header.SetBytesKV(headerName, hack.StringToSlice(c.OriginRequest().RemoteIP().String()))
} else {
var buf bytes.Buffer
buf.Write(prevForward)
buf.WriteByte(',')
buf.WriteByte(' ')
buf.WriteString(c.OriginRequest().RemoteIP().String())
c.ForwardRequest().Header.SetBytesKV(headerName, buf.Bytes())
}

return f.BaseFilter.Pre(c)
}

0 comments on commit bc62910

Please sign in to comment.