mirror of
https://github.com/gin-gonic/gin.git
synced 2026-07-13 22:52:20 +08:00
Compare commits
4 Commits
1614fbd96c
...
75bc03727b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
75bc03727b | ||
|
|
9914178584 | ||
|
|
915e4c90d2 | ||
|
|
fbd60bfe6b |
29
binding/decimal.go
Normal file
29
binding/decimal.go
Normal file
@ -0,0 +1,29 @@
|
||||
package binding
|
||||
|
||||
import (
|
||||
"github.com/shopspring/decimal"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// CustomDecimal represents a decimal number that can be bound from form values.
|
||||
// It supports values with leading dots (e.g. ".1" is parsed as "0.1").
|
||||
type CustomDecimal struct {
|
||||
decimal.Decimal
|
||||
}
|
||||
|
||||
// UnmarshalParam implements the binding.BindUnmarshaler interface.
|
||||
// It converts form values to decimal.Decimal, with special handling for
|
||||
// values that start with a dot (e.g. ".1" becomes "0.1").
|
||||
func (cd *CustomDecimal) UnmarshalParam(val string) error {
|
||||
if strings.HasPrefix(val, ".") {
|
||||
val = "0" + val
|
||||
}
|
||||
|
||||
dec, err := decimal.NewFromString(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cd.Decimal = dec
|
||||
return nil
|
||||
}
|
||||
59
binding/decimal_test.go
Normal file
59
binding/decimal_test.go
Normal file
@ -0,0 +1,59 @@
|
||||
package binding
|
||||
|
||||
import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCustomDecimalUnmarshalParam(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
want string
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "leading dot",
|
||||
input: ".1",
|
||||
want: "0.1",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "invalid decimal",
|
||||
input: "abc",
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "empty string",
|
||||
input: "",
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "leading dot with multiple digits",
|
||||
input: ".123",
|
||||
want: "0.123",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "normal decimal",
|
||||
input: "1.23",
|
||||
want: "1.23",
|
||||
wantErr: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var cd CustomDecimal
|
||||
err := cd.UnmarshalParam(tt.input)
|
||||
|
||||
if tt.wantErr {
|
||||
assert.Error(t, err)
|
||||
return
|
||||
}
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, tt.want, cd.String())
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -989,7 +989,8 @@ func (c *Context) ClientIP() string {
|
||||
|
||||
if trusted && c.engine.ForwardedByClientIP && c.engine.RemoteIPHeaders != nil {
|
||||
for _, headerName := range c.engine.RemoteIPHeaders {
|
||||
ip, valid := c.engine.validateHeader(c.requestHeader(headerName))
|
||||
headerValue := strings.Join(c.Request.Header.Values(headerName), ",")
|
||||
ip, valid := c.engine.validateHeader(headerValue)
|
||||
if valid {
|
||||
return ip
|
||||
}
|
||||
|
||||
@ -1143,6 +1143,37 @@ func TestContextRenderNoContentIndentedJSON(t *testing.T) {
|
||||
assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
|
||||
}
|
||||
|
||||
func TestContextClientIPWithMultipleHeaders(t *testing.T) {
|
||||
c, _ := CreateTestContext(httptest.NewRecorder())
|
||||
c.Request, _ = http.NewRequest(http.MethodGet, "/test", nil)
|
||||
|
||||
// Multiple X-Forwarded-For headers
|
||||
c.Request.Header.Add("X-Forwarded-For", "1.2.3.4, "+localhostIP)
|
||||
c.Request.Header.Add("X-Forwarded-For", "5.6.7.8")
|
||||
c.Request.RemoteAddr = localhostIP + ":1234"
|
||||
|
||||
c.engine.ForwardedByClientIP = true
|
||||
c.engine.RemoteIPHeaders = []string{"X-Forwarded-For"}
|
||||
_ = c.engine.SetTrustedProxies([]string{localhostIP})
|
||||
|
||||
// Should return 5.6.7.8 (last non-trusted IP)
|
||||
assert.Equal(t, "5.6.7.8", c.ClientIP())
|
||||
}
|
||||
|
||||
func TestContextClientIPWithSingleHeader(t *testing.T) {
|
||||
c, _ := CreateTestContext(httptest.NewRecorder())
|
||||
c.Request, _ = http.NewRequest(http.MethodGet, "/test", nil)
|
||||
c.Request.Header.Set("X-Forwarded-For", "1.2.3.4, "+localhostIP)
|
||||
c.Request.RemoteAddr = localhostIP + ":1234"
|
||||
|
||||
c.engine.ForwardedByClientIP = true
|
||||
c.engine.RemoteIPHeaders = []string{"X-Forwarded-For"}
|
||||
_ = c.engine.SetTrustedProxies([]string{localhostIP})
|
||||
|
||||
// Should return 1.2.3.4
|
||||
assert.Equal(t, "1.2.3.4", c.ClientIP())
|
||||
}
|
||||
|
||||
// Tests that the response is serialized as Secure JSON
|
||||
// and Content-Type is set to application/json
|
||||
func TestContextRenderSecureJSON(t *testing.T) {
|
||||
@ -1910,7 +1941,7 @@ func TestContextClientIP(t *testing.T) {
|
||||
resetContextForClientIPTests(c)
|
||||
|
||||
// IPv6 support
|
||||
c.Request.RemoteAddr = "[::1]:12345"
|
||||
c.Request.RemoteAddr = fmt.Sprintf("[%s]:12345", localhostIPv6)
|
||||
assert.Equal(t, "20.20.20.20", c.ClientIP())
|
||||
|
||||
resetContextForClientIPTests(c)
|
||||
@ -3212,7 +3243,7 @@ func TestContextCopyShouldNotCancel(t *testing.T) {
|
||||
}()
|
||||
|
||||
addr := strings.Split(l.Addr().String(), ":")
|
||||
res, err := http.Get(fmt.Sprintf("http://127.0.0.1:%s/", addr[len(addr)-1]))
|
||||
res, err := http.Get(fmt.Sprintf("http://%s:%s/", localhostIP, addr[len(addr)-1]))
|
||||
if err != nil {
|
||||
t.Error(fmt.Errorf("request error: %w", err))
|
||||
return
|
||||
|
||||
31
examples/custom-decimal/main.go
Normal file
31
examples/custom-decimal/main.go
Normal file
@ -0,0 +1,31 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type QueryParams struct {
|
||||
Amount binding.CustomDecimal `form:"amount"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
r := gin.Default()
|
||||
|
||||
r.GET("/amount", func(c *gin.Context) {
|
||||
var params QueryParams
|
||||
if err := c.BindQuery(¶ms); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"amount": params.Amount.String(),
|
||||
})
|
||||
})
|
||||
|
||||
r.Run(":8080")
|
||||
}
|
||||
@ -83,7 +83,7 @@ func TestLoadHTMLGlobDebugMode(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestH2c(t *testing.T) {
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
ln, err := net.Listen("tcp", localhostIP+":0")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
6
utils.go
6
utils.go
@ -19,6 +19,12 @@ import (
|
||||
// BindKey indicates a default bind key.
|
||||
const BindKey = "_gin-gonic/gin/bindkey"
|
||||
|
||||
// localhostIP indicates the default localhost IP address.
|
||||
const localhostIP = "127.0.0.1"
|
||||
|
||||
// localhostIPv6 indicates the default localhost IPv6 address.
|
||||
const localhostIPv6 = "::1"
|
||||
|
||||
// Bind is a helper function for given interface object and returns a Gin middleware.
|
||||
func Bind(val any) HandlerFunc {
|
||||
value := reflect.ValueOf(val)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user