Hey Folks!
I have a typescripts background and try to switch to Go now. Unfortunately I have some problems wrapping my head around data modelling without generics and inheritance. I am trying to write an API that handles the following requests:
GET /forms/myform
{
"title": "Hello",
"fields": [
{
"type": "textField",
"name": "ip",
"value": "192.168.1.2",
"label": "My IP",
"errorMessage": ""
},
{
"type": "range",
"name": "interval",
"value": 1000,
"label": "SomeInterval",
"errorMessage": ""
}
]
}
I managed to write a handler for the GET request thanks to the empty interface.
I need to handle Patch requests as well. The request body will contain an object of key, value pairs like so:
{
"ip": "192.168.1.60",
"interval": 4020
}
The expected outcome would be the updated form:
{
"title": "Hello",
"fields": [
{
"type": "textField",
"name": "ip",
"value": "192.168.1.60",
"label": "My IP",
"errorMessage": ""
},
{
"type": "range",
"name": "interval",
"value": 4020,
"label": "SomeInterval",
"errorMessage": ""
}
]
}
In case the user sends an invalid request like so:
{
"ip": "192.168.1.3abc",
"interval": 50000
}
The expected response would be:
{
"title": "Hello",
"fields": [
{
"type": "textField",
"name": "ip",
"value": "192.168.1.3abc",
"label": "My IP",
"errorMessage": "The field ip must be a valid IPv4"
},
{
"type": "range",
"name": "interval",
"value": 60000,
"label": "SomeInterval",
"errorMessage": "The interval is not allowed to be greater than 5000"
}
]
}
I think you get the point. My main problem is how would one model this in Go? How would I bind the input struct to the slice or array containing the fields. Or would I bind to a RequestStruct and then map this to my fields slice? I have tried different approaches like storing the fields as a struct with an index field and marshalling them to a JSON array in the end and fiddling around with reflection etc. All my approaches seem wrong or feel unnatural. Unfortunately I could not find an example online and I hope that someone more experienced can point me in the right direction.
Thanks