URL查询参数编码问题(golang)

主要是后端有个转发请求的功能,对另一个服务请求时url query参数有乱码(字符编码),导致另一个服务响应500.
前端传入的是json
"json": "{\"page_index\":1,\"page_size\":20}"
后端解析json并且转为query params 发起http request。这里对传入params的value的类型断言:

switch params[i].Value.(type) {
case float64:
	fmt.Println("float64")
	q.Add(params[i].Key, strconv.FormatFloat(params[i].Value.(float64), 'E', -1, 64))
	fmt.Println(strconv.FormatFloat(params[i].Value.(float64), 'E', -1, 64))
	break
...
}

打印显示:

float64
1E+00
float64
2E+01

对应的query url就会是:
page_index=1E%2B00&page_size=2E%2B01
因为strconv.FormatFloat中的fmt设置为了’E’,在这个函数里可以看到说明:

// FormatFloat converts the floating-point number f to a string,
// according to the format fmt and precision prec. It rounds the
// result assuming that the original was obtained from a floating-point
// value of bitSize bits (32 for float32, 64 for float64).
//
// The format fmt is one of
// 'b' (-ddddp±ddd, a binary exponent),
// 'e' (-d.dddde±dd, a decimal exponent),
// 'E' (-d.ddddE±dd, a decimal exponent),
// 'f' (-ddd.dddd, no exponent),
// 'g' ('e' for large exponents, 'f' otherwise),
// 'G' ('E' for large exponents, 'f' otherwise),
// 'x' (-0xd.ddddp±ddd, a hexadecimal fraction and binary exponent), or
// 'X' (-0Xd.ddddP±ddd, a hexadecimal fraction and binary exponent).
//
// The precision prec controls the number of digits (excluding the exponent)
// printed by the 'e', 'E', 'f', 'g', 'G', 'x', and 'X' formats.
// For 'e', 'E', 'f', 'x', and 'X', it is the number of digits after the decimal point.
// For 'g' and 'G' it is the maximum number of significant digits (trailing
// zeros are removed).
// The special precision -1 uses the smallest number of digits
// necessary such that ParseFloat will return f exactly.
func FormatFloat(f float64, fmt byte, prec, bitSize int) string {
	return string(genericFtoa(make([]byte, 0, max(prec+4, 24)), f, fmt, prec, bitSize))
}

所以将E换为f,表示不使用指数形式,就可以获得正确的page值了

case float64:
	q.Add(params[i].Key, strconv.FormatFloat(params[i].Value.(float64), 'f', -1, 64))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值