Skip to content

Instantly share code, notes, and snippets.

@offlinehacker
Created May 21, 2023 08:39
Show Gist options
  • Save offlinehacker/71866bf710696fa190d676ee5f25bc1c to your computer and use it in GitHub Desktop.
Save offlinehacker/71866bf710696fa190d676ee5f25bc1c to your computer and use it in GitHub Desktop.
Automerge golang example
package main
import (
"fmt"
"time"
"github.com/automerge/automerge-go"
)
type S struct {
Counter int64 `json:"counter"`
}
func runPeer(name string, recvChan chan []byte, sendChan chan []byte, enableIncr bool) {
doc := automerge.New()
syncState := automerge.NewSyncState(doc)
loop:
for {
select {
case msg, ok := <-recvChan:
if !ok {
break loop
}
fmt.Printf("[%s] peer recv\n", name)
if err := syncState.ReceiveMessage(msg); err != nil {
panic(err)
}
case <-time.After(time.Millisecond):
if enableIncr {
if err := doc.Path("counter").Counter().Inc(1); err != nil {
panic(err)
}
}
s, err := automerge.As[*S](doc.Root())
if err != nil {
panic(err)
}
fmt.Printf("[%s] counter: %d\n", name, s.Counter)
fmt.Printf("[%s] doc head: %v\n", name, doc.Heads())
fmt.Printf("[%s] doc size: %d\n", name, len(doc.Save()))
}
msg, valid := syncState.GenerateMessage()
if valid {
fmt.Printf("[%s] peer sending: %d bytes\n", name, len(msg))
sendChan <- msg
}
}
}
func main() {
chan1 := make(chan []byte, 1)
chan2 := make(chan []byte, 1)
go runPeer("peer1", chan1, chan2, true)
runPeer("peer2", chan2, chan1, false)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment