Answer the question
In order to leave comments, you need to log in
How to pass any type of data in filtering?
A couple of notes at once:
- I have no experience in languages with static typing
- the question is not how to solve the problem, but how to find a good standard solution
- if there are any hacks specifically in go for such tasks - then they not particularly interesting, because the same data (data structure) will need to be done in gRPC.
The essence of the task: it is necessary to pass data for filtering, with two parameters: a field by which filtering will be done, and a value by which data will be selected from the database. Since the field can be of any type, the data can be of any type: string, int, bool, etc.
The solution that came up right away was to pass the value as a separate object (structure), which will indicate what type this value is:
{
"type": "string",
"value": {
"string": "filter value",
"int": 0,
"bool": false
}
}
{
"filed": "field_name",
"value": {
"type": "int",
"value": {
"string": "",
"int": 100,
"bool": false
}
}
}
Answer the question
In order to leave comments, you need to log in
In Go, you cannot use a string value as a type qualifier. That is, you cannot write:
var Type string
Type = "int"
var foo Type // так не работает
var foo "int" // и так не работает
type Message struct {
Type string
Payload json.RawMessage // разобрать со второго захода
}
var message Message
// первый заход, Payload пока не парсится, остаётся json.RawMessage
json.Unmarshal(data, message)
// варианты типа
switch message.Type {
case "string":
dst = new(StringPayload) // готовим контейнер для типа string
case "int":
dst = new(IntPayload) // контейнер для int
}
// теперь разбираем Payload в подходящий контейнер
json.Unmarshal(message.Payload, dst)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question