如何在Golang Gin框架中获取紧凑格式的HTTP POST请求原始数据
问题描述
我的服务器收到一个Content-Type为application/json的POST请求,请求载荷如下:
{ "amount": 10000, "amount_due": 0, "amount_paid": 10000, "attempts": 1 }
出于计算需求,我需要将该载荷转换为无空格、无换行的紧凑JSON文本,目标格式如下:
{"amount":10000,"amount_due":0,"amount_paid":10000,"attempts":1}
我使用Golang及Gin框架开发,尝试通过ginCtx.Request.Body或ginCtx.GetRawData()获取请求体,但得到的是带缩进格式的JSON,无法满足需求。请告诉我如何实现目标。
解决方案
方法一:解析为结构体后重新序列化(推荐)
这种方式先将带格式的JSON解析为Go结构体,再用标准库json.Marshal()生成紧凑格式的JSON,能避免直接操作字符串可能带来的格式错误(比如转义字符、非法JSON语法问题)。
- 定义对应请求载荷的结构体:
type PaymentRequest struct { Amount int `json:"amount"` AmountDue int `json:"amount_due"` AmountPaid int `json:"amount_paid"` Attempts int `json:"attempts"` }
- 在Gin处理函数中实现逻辑:
import ( "encoding/json" "net/http" "github.com/gin-gonic/gin" ) func handlePayment(c *gin.Context) { var req PaymentRequest // 将请求体绑定到结构体 if err := c.ShouldBindJSON(&req); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } // 序列化生成紧凑JSON compactJSON, err := json.Marshal(req) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } // 转换为字符串使用,compactJSON即为符合要求的字节数组 compactStr := string(compactJSON) // 后续计算逻辑... }
方法二:直接处理原始JSON数据(无需定义结构体)
如果不想提前定义结构体,可以将原始JSON解析为map[string]interface{}后再序列化:
func handlePayment(c *gin.Context) { rawData, err := c.GetRawData() if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } var data map[string]interface{} if err := json.Unmarshal(rawData, &data); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } compactJSON, err := json.Marshal(data) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } compactStr := string(compactJSON) // 后续计算逻辑... }
关键注意事项
- 不要直接用字符串替换空格和换行,因为JSON的字符串值中可能包含合法的空格/换行,直接替换会破坏数据完整性。
json.Marshal()默认输出无缩进、无多余空格的紧凑JSON,完全匹配你的需求。
内容的提问来源于stack exchange,提问作者Abhay Kumar
相关产品推荐
相关产品推荐

