0

TLDR: Can I register callback functions in golang to get notified if a struct member is changed?


I would like to create a simple two-way-binding between a go server and an angular client. The communication is done via websockets.

Example:

Go:

type SharedType struct {
    A int
    B string
}
sharedType := &SharedType{}
...
sharedType.A = 52

JavaScript:

var sharedType = {A: 0, B: ""};
...
sharedType.A = 52;

Idea:

In both cases, after modifying the values, I want to trigger a custom callback function, send a message via the websocket, and update the value on the client/server side accordingly.

The sent message should only state which value changed (the key / index) and what the new value is. It should also support nested types (structs, that contain other structs) without the need of transmitting everything.

On the client side (angular), I can detect changes of JavaScript objects by registering a callback function.

On the server side (golang), I could create my own map[] and slice[] implementations to trigger callbacks everytime a member is modified (see the Cabinet class in this example: https://appliedgo.net/generics/).

Within these callback-functions, I could then send the modified data to the other side, so two-way binding would be possible for maps and slices.

My Question:

I would like to avoid things like

sharedType.A = 52
sharedType.MemberChanged("A")
// or:
sharedType.Set("A", 52) //.. which is equivalent to map[], just with a predifined set of allowed keys

Is there any way in golang to get informed if a struct member is modified? Or is there any other, generic way for easy two-way binding without huge amounts of boiler-plate code?

4

1 回答 1

1

不,这是不可能的。


但真正的问题是:你打算如何在你的 Go 程序中使用所有这些魔法?

考虑一下你想要的东西确实是可能的。现在是一个无辜的任务

v.A = 42

会——除其他外——触发通过 websocket 连接向客户端发送内容。

现在如果连接关闭(客户端断开)并且发送失败会发生什么?如果在截止日期之前无法完成发送会怎样?

好的,假设您至少部分正确,并且只有在发送成功时才会对本地字段进行实际修改。不过,应该如何处理发送错误?

说,如果第三次分配会发生什么

 v.A = 42
 v.B = "foo"
 v.C = 1e10-23

失败?

于 2017-02-03T11:42:48.243 回答