Golang结构体的双向绑定

huangapple go评论84阅读模式
英文:

Two-way-binding for golang structs

问题

TLDR:我可以在Go中注册回调函数来在结构成员更改时得到通知吗?

我想在Go服务器和Angular客户端之间创建一个简单的双向绑定。通信通过Websockets完成。

示例:

Go:

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

JavaScript:

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

想法:

在这两种情况下,修改值后,我希望触发一个自定义的回调函数,通过Websockets发送一条消息,并相应地更新客户端/服务器端的值。

发送的消息应该只说明哪个值发生了变化( / 索引),以及新值是什么。它还应该支持嵌套类型(包含其他结构的结构),而无需传输所有内容。

在客户端(Angular)上,我可以通过注册回调函数来检测JavaScript对象的更改。

在服务器端(Go语言)上,我可以创建自己的map[]slice[]实现,以便在每次修改成员时触发回调(请参阅此示例中的Cabinet类:https://appliedgo.net/generics/)。

在这些回调函数中,我可以将修改后的数据发送到另一端,从而实现映射和切片的双向绑定。

我的问题:

我想避免这样的事情:

sharedType.A = 52
sharedType.MemberChanged("A")
// 或者:
sharedType.Set("A", 52) //.. 这相当于map[],只是有一组预定义的允许键

在Go语言中是否有任何方法可以在结构成员修改时得到通知或者是否有其他通用的简便双向绑定方法而不需要大量的样板代码

<details>
<summary>英文:</summary>

**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 := &amp;SharedType{}
    ...
    sharedType.A = 52

JavaScript:

    var sharedType = {A: 0, B: &quot;&quot;};
    ...
    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(&quot;A&quot;)
    // or:
    sharedType.Set(&quot;A&quot;, 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?


</details>


# 答案1
**得分**: 1

这是不可能的

----

但真正的问题是你打算如何在你的Go程序中使用这样的魔法

考虑一下如果你想要的确实是可能的
现在一个无辜的赋值语句

    v.A = 42

会触发一些操作比如将数据发送到客户端的websocket连接

那么如果连接关闭客户端断开连接),发送失败会发生什么
如果发送在截止时间之前未能完成会怎么样

好吧假设你至少在某种程度上做对了只有在发送成功后才会实际修改本地字段
但是应该如何处理发送错误呢

比如在以下赋值语句中如果第三个赋值

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

失败了应该发生什么

<details>
<summary>英文:</summary>

No, it&#39;s not possible.

----

But the real question is: how do you suppose to wield all such magic in your Go program?

Consider what you&#39;d like to have would be indeed possible.
Now an innocent assignment

    v.A = 42

would&amp;mdash;among other things&amp;mdash;trigger sending stuff
over a websocket connection to the client.

Now what happens if the connection is closed (client disconnected),
and the sending fails?
What happens if sending fails to complete before a deadline is reached?

OK, suppose you get it at least partially right and actual modification of the local field happens only if sending succeeds.
Still, how should sending errors be handled?

Say, what should happen if the third assignment in

     v.A = 42
     v.B = &quot;foo&quot;
     v.C = 1e10-23

fails?


</details>



# 答案2
**得分**: 0

你可以尝试使用服务器发送事件SSE将实时数据发送到前端同时通过发送单个 POST 请求来进行更改这样你可以在后台监视并每秒发送数据

<details>
<summary>英文:</summary>

you could try using server sent events (SSE) to send realtime data to the frontend, while sending a single post request with ur changes. That way you can monitor in the back and send data every second.

</details>



huangapple
  • 本文由 发表于 2017年2月3日 18:30:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/42022128.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定