curl POST请求数据被截断?Go Gin教程调试遇异常
解决curl发送JSON POST请求时的参数解析错误
问题场景
我正在学习Go语言,目前在完成官方的Web服务Gin教程。运行测试POST请求处理的curl命令时出现错误,调试发现只有部分JSON体被正确包含在--data参数中。用Postman发送相同请求能正常运行,当前使用的是最新版curl。
错误信息
HTTP/1.1 200 OK Date: Wed, 26 Jul 2023 22:34:49 GMT Content-Length: 0 curl: (6) Could not resolve host: Modern curl: (6) Could not resolve host: Sound curl: (6) Could not resolve host: of curl: (6) Could not resolve host: Betty curl: (3) URL using bad/illegal format or missing URL curl: (3) unmatched close brace/bracket in URL position 20: Carter,price: 49.99} ^
使用的curl命令
curl http://localhost:8080/albums --include --header "Content-Type: application/json" --request "POST" --data '{"id": "4","title": "The Modern Sound of Betty Carter","artist": "Betty Carter","price": 49.99}'
问题原因
shell会将单引号包裹的字符串中的空格视为参数分隔符,导致JSON内容被拆分成多个部分,后续部分被curl误识别为新的URL,从而引发解析错误。
解决办法
方案一:转义双引号并用双引号包裹JSON
将整个JSON用双引号包裹,同时转义内部的双引号,避免shell解析空格:
curl http://localhost:8080/albums --include --header "Content-Type: application/json" --request "POST" --data "{\"id\": \"4\",\"title\": \"The Modern Sound of Betty Carter\",\"artist\": \"Betty Carter\",\"price\": 49.99}"
方案二:使用ANSI-C引号(适用于bash/zsh)
在单引号前添加$,让shell正确解析包含空格的字符串:
curl http://localhost:8080/albums --include --header "Content-Type: application/json" --request "POST" --data $'{"id": "4","title": "The Modern Sound of Betty Carter","artist": "Betty Carter","price": 49.99}'
方案三:通过文件传递JSON
将JSON内容写入单独的文件(比如data.json),再通过@参数引用文件:
curl http://localhost:8080/albums --include --header "Content-Type: application/json" --request "POST" --data @data.json
data.json的内容:
{"id": "4","title": "The Modern Sound of Betty Carter","artist": "Betty Carter","price": 49.99}
内容的提问来源于stack exchange,提问作者Thoven
相关产品推荐
相关产品推荐

