mardi 5 novembre 2019

Handling request body with different types in golang

Let's say backend application has such request. As you can see this is an array of objects.

[
    {
        "section_id": "8ad1f7cc-a510-48ee-b4fa-bedbee444a84", // (uuid - string)
        "section_name": "First section"
    },
    {
        "section_id": 1556895, // (int)
        "section_name": "Second section"
    }
]

I want to parse this array. Depending on the section id type, application need to do different things. How to bypass strict typing?

requestBody, err := ioutil.ReadAll(request.Body)

if err = json.Unmarshal([]byte(requestBody), &sections); err != nil {
    println(err)
}

for _, section := range sections {
    if reflect.TypeOf(section.ID) == string {
        // block 1
    } reflect.TypeOf(section.ID) == int {
        // block 2
    }
}




Aucun commentaire:

Enregistrer un commentaire