'Golang field type validation

I have a struct

type InputData struct {
   SomeNumber  int     `json:"someNumber"`
   SomeText    string  `json:"someText"`
}

I do json.Unmarshal my http request body into a struct of type InputData.

In case I pass in {"someNumber": "NaN", "someText": 42} I get something like

panic: json: cannot unmarshal string into Go struct field InputData.someNumber of type int

Is there a way to get complete and more structured error data?

For instance, a list of all the non-parseable fields along w/ the reason for that? (in my example, I'd like to know that someNumber is invalid because I passed in a string AND that someText is invalid because I passed in a number)

I doubt that's possible, but I'd still like to validate my input in that sense. Is it a use case for JSON-Schema validation?

go


Solution 1:[1]

Yes, this is probably a good use-case for JSON Schema validation. You can generate a JSON Schema directly from your Go struct and then use a validation library to get more useful errors. For example, using Huma's JSON Schema package with the excellent xeipuuv/gojsonschema:

package main

import (
    "fmt"
    "reflect"

    "github.com/danielgtaylor/huma/schema"
    "github.com/xeipuuv/gojsonschema"
)

type InputData struct {
    SomeNumber int    `json:"someNumber"`
    SomeText   string `json:"someText"`
}

func main() {
    // Generate a JSON Schema from the struct type.
    s, err := schema.Generate(reflect.TypeOf(InputData{}))
    if err != nil {
        panic(err)
    }

    // Get the input from the user
    input := []byte(`{"someNumber": "NaN", "someText": 42}`)

    // Load the schema and validate the user's input as bytes which
    // means we don't have to handle invalid types by first unmarshaling.
    loader := gojsonschema.NewGoLoader(s)
    doc := gojsonschema.NewBytesLoader(input)
    validator, err := gojsonschema.NewSchema(loader)
    if err != nil {
        panic(err)
    }
    result, err := validator.Validate(doc)
    if err != nil {
        panic(err)
    }

    // Display the results!
    if !result.Valid() {
        for _, desc := range result.Errors() {
            fmt.Printf("%s (%s)\n", desc, desc.Value())
        }
        return
    }

    fmt.Println("Input was valid!")
}

Full example: https://go.dev/play/p/XEnrQswp_7N. Output looks like:

someNumber: Invalid type. Expected: integer, given: string (NaN)
someText: Invalid type. Expected: string, given: integer (42)

The ResultError struct has a whole bunch of information about each error that occurs.

Solution 2:[2]

Using https://github.com/marrow16/valix (https://pkg.go.dev/github.com/marrow16/valix) it could be achieved with the following:

package main

import (
    "fmt"
    "github.com/marrow16/valix"
    "testing"
)

type InputData struct {
    SomeNumber int    `json:"someNumber"`
    SomeText   string `json:"someText"`
}

var validator = valix.MustCompileValidatorFor(InputData{}, nil)

func TestInputDataValidation(t *testing.T) {
    myInputData := &InputData{}
    str := `{"someNumber": "NaN", "someText": 43}`
        
    ok, violations, _ := validator.ValidateStringInto(str, myInputData)
    println("Validated OK? ", ok)
    if !ok {
        for i, v := range violations {
            fmt.Printf("Violation #%d: Property='%s', Message='%s'\n", i+1, v.Property, v.Message)
        }
    }
}

Would output:

Validated OK? false
Violation #1: Property='someNumber', Message='Value expected to be of type number'
Violation #2: Property='someText', Message='Value expected to be of type string'

Disclosure: I am the author of Valix

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2