结构标签是否对API用户抛出错误?

huangapple go评论75阅读模式
英文:

Do struct tags throw error to the API user?

问题

type Person struct {
  Id       string
  Roll_no  int
  Email    string  `json:"email" validate:"required"`
}

这里的email是必需的。如果用户在API调用的请求体中没有提供该字段,Go语言会自动处理名称验证并在未提供该字段时抛出错误吗?还是我需要在代码中手动验证并以某种形式抛出错误,比如HTTP状态码?

英文:
type Person struct {
  Id       string
  Roll_no  int
  Email    string  `json:"email" validate:"required"`
}

The email here is required. If the user does not provide that in the request body of the API call, will Go handle the name validation automatically and throw the error if this field is not provided? Or would i neeI to validate it manually in my code and throw the error in some form of a http status code?

答案1

得分: 2

如果通过API发送的JSON不包含Email字段,那么encoding/json中的json.Unmarshal函数会将其视为Email是一个空字符串。

选项A:如果空字符串不是一个有效的Email,你可以在json.Unmarshal之后检查是否为空字符串。

	var person Person
	
	err := json.Unmarshal(jsonBlob, &person)
	if err != nil{
		return err
	}
	
	if person.Email == "" {
		return errors.New("email cannot be empty")
	}

选项B:如果空字符串是有效的,你可以创建一个自定义的MarshalJSON函数来将JSON解析为字符串,并查找Email键。

https://pkg.go.dev/encoding/json#example-package-CustomMarshalJSON

英文:

If the JSON sent over API does not contain Email then encoding/json json.Unmarshal will treat it as if Email was an empty string.

Option A: If empty string is not a valid Email, you can check for an empty string after json.Unmarshal

	var person Person
	
	err := json.Unmarshal(jsonBlob, &person)
	if err != nil{
		return err
	}
	
	if person.Email == "" {
		return errors.New("email cannon be empty"
	}

Option B: If empty string is valid, you can create a custom MarshalJSON to parse JSON as a string and look for the Email key.

https://pkg.go.dev/encoding/json#example-package-CustomMarshalJSON

答案2

得分: 2

结构标签是否会向API用户抛出错误?

不会。有很多原因。

  1. 一些结构标签(例如json标签)仅由encoding/json包使用,用于映射JSON对象元素和结构字段之间的关系。

  2. 其他结构标签(如validate标签)由某些第三方包使用,如果您不使用该包,将不会发生任何事情。

  3. Go语言(包括其标准库)是“无魔法”的。没有任何神奇的事情会发生。如果您需要在API端点上进行验证,可以使用验证包来检查结构标签,但这不会自动发生:您必须调用这些函数并自己返回API错误。不,我不会在这里推荐任何框架。

  4. 要使结构标签起作用,它们必须是有效的,而您的标签都不是有效的。运行go vet命令以找到此类问题。(应该是json:"email" validate:"required",可能还应该是email

  5. 在Go中,错误根本不会被“抛出”。特别是具有400 Bad Request状态码的HTTP响应不会被“抛出”。正确使用术语总是有帮助的。

英文:

> Do struct tags throw error to the API user?

No. For a lot of reasons.

  1. Some struct tags (e.g. the json ones) are just used by package encoding/json to map between JSON object elements and struct fields).

  2. Other struct tags (like validate) are used by certain 3rd party packages and if you do not use that package nothing at all will happen.

  3. Go (the language and its stdlib) is "free from magic". Nothing magically happens. If you need validation on your API endpoints you might use validation packages which inspect struct tags but this won't happen magically: You have to call these functions and return an API error yourself. And no, I won't recommend a framework here.

  4. To work struct tags have to be valid, none of yours are. Run go vet to find this type of problem. (should be json:"emal" validate:"required" and probably even "email")

  5. Errors in Go are not "thrown" at all. Especially HTTP responses with a status code of 400 Bad Request are not "thrown". It always helps to get the terminology correct).

huangapple
  • 本文由 发表于 2022年4月26日 08:40:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/72007126.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定