Home > Back-end >  Do struct tags throw error to the API user?
Do struct tags throw error to the API user?

Time:04-26

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

since, the email here is required, so if the user does not provide that in the API call's request body json, will the golang handle the name validation automatically and throw the error if this field is not provided, or would i need to validate it manually in my code and throw the error in some form of a http status code?

CodePudding user response:

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

CodePudding user response:

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).

  • Related