H
H
HellWalk2022-01-27 12:59:32
go
HellWalk, 2022-01-27 12:59:32

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
    }
}


And the filtering data as a whole will look like this:

{
    "filed": "field_name",
    "value": {
        "type": "int",
        "value": {
            "string": "",
            "int": 100,
            "bool": false
        }
    }
}


Well, the logic of working with such a format is clear - we look at what type of data, and we get its value from the desired field.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
uvelichitel, 2022-01-27
@uvelichitel

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" // и так не работает

Of the languages ​​​​known to me, this is nowhere possible.
In your specific example, snippets are similar to JSON. In Go, this is parsed like this:
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)

gRPC usually uses protobuf as a message container. protobuf is a strongly typed language. It is unlikely that it will be possible to transfer a generic message on it, at least I have not seen what anyone would do.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question