Golang,Gin框架使用ShouldBindJSON时出现EOF报错

前言

做毕设ing,使用的是Gin框架做的一个简单的管理系统。但偶尔也会碰到一些稀奇古怪的Bug,因此记录一下。

问题描述

api是这样写的

go 复制代码
func UserRegisterHandler(c *gin.Context, user *usecase.UserOperate) {

	if err := c.ShouldBindJSON(&UserRegisterRequest); err != nil {
		log.Error("eeeeeeeeeee", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	userID, err := user.Register(c, UserRegisterRequest.Username, UserRegisterRequest.Password, UserRegisterRequest.Phone)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"userID": userID})
}

其中结构体定义为

go 复制代码
var UserRegisterRequest struct {
	Username string `json:"username"`
	Password string `json:"password"`
	Phone    string `json:"phone"`
}

Postman请求会报错EOF,确定是在ShouldBindJSON的地方出现了错误。

问题解决

先是发现自己忘记了加required标签...

修改后:

go 复制代码
type UserRegisterRequest struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
	Phone    string `json:"phone" binding:"required"`
}

同时换成了更简单的ShouldBind。发现报错改为:

go 复制代码
Key: 'UserRegisterRequest.Password' Error:Field validation for 'Password' failed on the 'required' tag

遂搜索,参考https://blog.csdn.net/default7/article/details/114920194

发现是自己忘记了定义form...

修改后最终为:

go 复制代码
type UserRegisterRequest struct {
	Username string ` form:"username" json:"username" binding:"required"`
	Password string `form:"password" json:"password" binding:"required"`
	Phone    string `form:"phone" json:"phone" binding:"required"`
}

func UserRegisterHandler(c *gin.Context, user *usecase.UserOperate) {
	var userRegisterRequest UserRegisterRequest

	if err := c.ShouldBind(&userRegisterRequest); err == nil {
		c.JSON(http.StatusOK, gin.H{
			"user":     userRegisterRequest.Username,
			"password": userRegisterRequest.Password,
			"phone":    userRegisterRequest.Phone,
		})
	} else {
		log.Error("绑定JSON错误", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	userID, err := user.Register(c, userRegisterRequest.Username, userRegisterRequest.Password, userRegisterRequest.Phone)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"userID": userID})
}

成功!

总结反思

定义时候注意细节...Go的反引号标签要用好。

相关推荐
Data_Journal10 小时前
Scrapyd:分步教程
开发语言·python·microsoft·golang·编辑器·html·iphone
程序员小八77713 小时前
Go Web 工程化:日志、配置与错误处理中间件,让服务「能上线」
前端·中间件·golang
2601_962070233 天前
差异基因富集分析(R语言——GO&KEGG&GSEA)
开发语言·golang·r语言
「、皓子~3 天前
海狸IM 2.1 正式发布
flutter·微服务·golang·electron·开源软件·im·海狸im
运维开发笔记3 天前
8.1 Go Struct 结构体基础
golang
ttwuai3 天前
Go 后台接入 CAS 单点登录后,原来的权限怎么继续生效?
开发语言·后端·golang
蓝宝石的傻话3 天前
因为MiBeeNVR,决定接 onvif-go 自己管理并重构
数码相机·重构·golang
念何架构之路4 天前
Gin辅助模块与学习路径
学习·gin
ttwuai4 天前
Go 后台管理系统组件库文档怎么写,才不会坑后续维护?
开发语言·javascript·golang