验证PATCH HTTP请求中的单个字段
时间:2024-02-22
浏览:372
作者:佚名
珍惜时间,勤奋学习!今天给大家带来《验证PATCH HTTP请求中的单个字段》,正文内容主要涉及到等等,如果你正在学习Golang,或者是对Golang有疑问,欢迎大家关注我!后面我会持续更新相关内容的,希望都能帮到正在学习的大家!
问题内容
我有一个类似这样的结构片段
type Talent struct {
Code string `json:"code" gorm:"type:varchar(10);not null"`
FirstName string `json:"firstName" example:"Ravi" gorm:"type:varchar(50)"`
LastName string `json:"lastName" example:"Sharma" gorm:"type:varchar(50)"`
Email string `json:"email" example:"[email protected]" gorm:"type:varchar(100)"`
Contact string `json:"contact" example:"1234567890" gorm:"type:varchar(15)"`
AcademicYear *uint8 `json:"academicYear" example:"1" gorm:"type:tinyint(2)"`
Type *uint8 `json:"talentType" example:"4" gorm:"type:tinyint(2)"`
Resume *string `json:"resume" gorm:"type:varchar(200)"`
ExperienceInMonths *uint `json:"experienceInMonths"`
Image *string `json:"image" gorm:"type:varchar(200)"`
Gender *string `json:"gender" gorm:"type:varchar(50)"`
DateOfBirth *string `json:"dateOfBirth" gorm:"type:date"`
}
我想一次更新一个字段,所以我只将 json 中的一个字段作为 patch http 请求发送到 api,并在后端(golang)中将 json 转换为结构,其中仅在 json 中的该字段中将在结构中有价值...所有其他字段将为 nil。
例如,我正在发送firstname,现在当我将其转换为结构时,仅填充firstname字段。现在我想验证该字段..就像firstname是一个必填字段,因此它将有两个验证..一个用于检查其是否为空,另一个用于检查最大字符数。
同样,所有字段都有一些验证。现在我如何仅验证该特定字段。我考虑过使用 switch case,但是在 golang 中还有其他最佳方法吗?
正确答案
我也遇到过同样的情况,是这样解决的:
添加了 getjsonfields 方法来获取字符串数组中的 json 键
type book struct {
id int `json:"id"`
title string `json:"title" validate:"required"`
descr string `json:"description"`
thumbnailurl string `json:"thumbnail_url" validate:"required"`
createdat string `json:"created_at" validate:"required"`
}
func (b book) getjsonfields() []string
{
var jsonfields []string
val := reflect.valueof(b)
for i := 0; i < val.type().numfield(); i++ {
jsonfields = append(jsonfields, val.type().field(i).tag.get("json"))
}
return jsonfields
}
我还编写了一个小辅助函数来检查字符串是否包含:
func contains(stringslice []string, text string) bool {
for _, a := range stringslice {
if a == text {
return true
}
}
return false
}
这样就可以轻松编写简单的验证逻辑
// get url param id
book_id := mux.Vars(r)["id"]
// decode body
var generic map[string]interface{}
json.NewDecoder(r.Body).Decode(&generic)
// get json fields
jsonFields := new(models.Book).GetJsonFields()
// loop through the body
// if one key does not match -> return http.StatusBadRequest
for k, _ := range generic {
if contains(jsonFields, k) == false {
rw.WriteHeader(http.StatusBadRequest)
response := responses.BookResponse{Status: http.StatusBadRequest, Message: "error", Data: map[string]interface{}{"data": "a provided field is unknown."}}
json.NewEncoder(rw).Encode(response)
return
}
}今天关于《验证PATCH HTTP请求中的单个字段》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
12.01
12.01
热门专题
