简体   繁体   中英

Two-way-binding for golang structs

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?

No, it's not possible.


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

Consider what you'd like to have would be indeed possible. Now an innocent assignment

v.A = 42

would—among other things—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 = "foo"
 v.C = 1e10-23

fails?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM