Build a Commit Log Prototype

Distributed Services with Go — by Travis Jeffery (11 / 84)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Set Up the Project | TOC | Build a JSON over HTTP Server 👉

We’ll explore commit logs in depth in Chapter 3, Write a Log Package, when we build a persisted commit log library. For now, all you need to know about commit logs is that they’re a data structure for an append-only sequence of records, ordered by time, and you can build a simple commit log with a slice.

Create an internal/server directory tree in the root of your project and put the following code under the server directory in a file called log.go:

LetsGo/internal/server/log.go

​ ​package​ server

​ ​import​ (
​ ​"fmt"​
​ ​"sync"​
​ )

​ ​type​ Log ​struct​ {
​ mu sync.Mutex
​ records []Record
​ }

​ ​func​ NewLog() *Log {
​ ​return​ &Log{}
​ }

​ ​func​ (c *Log) Append(record Record) (​uint64​, ​error​) {
​ c.mu.Lock()
​ ​defer​ c.mu.Unlock()
​ record.Offset = ​uint64​(len(c.records))
​ c.records = append(c.records, record)
​ ​return​ record.Offset, nil
​ }

​ ​func​ (c *Log) Read(offset ​uint64​) (Record, ​error​) {
​ c.mu.Lock()
​ ​defer​ c.mu.Unlock()
​ ​if​ offset >= ​uint64​(len(c.records)) {
​ ​return​ Record{}, ErrOffsetNotFound
​ }
​ ​return​ c.records[offset], nil
​ }

​ ​type​ Record ​struct​ {
​ Value []​byte​ ​`json:"value"`​
​…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.