A framework to build clusters using the hashicorp's raft implementation.

Go - Rafting

Go Report Card License MIT Go Doc

A framework to build clusters using the hashicorp's raft implementation.

high quality video version

Install

go get -u github.com/danielgatis/go-rafting

And then import the package in your code:

import "github.com/danielgatis/go-rafting"

Usage

Create a new app state with some commands:

state := rafting.NewState(make(map[string]string))

state.Command("set", func(data interface{}, args map[string]interface{}) (interface{}, error) {
    d := data.(map[string]string)
    key := cast.ToString(args["key"])
    val := cast.ToString(args["val"])
    d[key] = val
    return val, nil
})

state.Command("get", func(data interface{}, args map[string]interface{}) (interface{}, error) {
    d := data.(map[string]string)
    key := cast.ToString(args["key"])
    return d[key], nil
})

state.Command("del", func(data interface{}, args map[string]interface{}) (interface{}, error) {
    d := data.(map[string]string)
    key := cast.ToString(args["key"])
    value := d[key]
    delete(d, key)
    return value, nil
})

Create a new raft node with a mdns discovery:

node, err := rafting.NewNode(rid, state.FSM(), rport, rafting.WithMdnsDiscovery())
if err != nil {
    logrus.Fatal(err)
}

Starting the node:

node.Start(context.Background())

Thats it!

Example

The example bellow is the code for the banner video.

package main

import (
	"context"
	"flag"
	"fmt"
	"time"

	"github.com/danielgatis/go-ctrlc"
	"github.com/danielgatis/go-rafting"
	"github.com/gofiber/fiber/v2"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cast"
)

var (
	rid   string
	rport int
	hport int
)

func init() {
	flag.StringVar(&rid, "rid", "1", "raft node id")
	flag.IntVar(&rport, "rport", 4001, "raft port number")
	flag.IntVar(&hport, "hport", 3001, "http port number")
}

func main() {
	flag.Parse()

	// raft node
	state := rafting.NewState(make(map[string]string))
	node, err := rafting.NewNode(rid, state.FSM(), rport, rafting.WithMdnsDiscovery())
	if err != nil {
		logrus.Fatal(err)
	}

	state.Command("set", func(data interface{}, args map[string]interface{}) (interface{}, error) {
		d := data.(map[string]string)
		key := cast.ToString(args["key"])
		val := cast.ToString(args["val"])
		d[key] = val
		return val, nil
	})

	state.Command("get", func(data interface{}, args map[string]interface{}) (interface{}, error) {
		d := data.(map[string]string)
		key := cast.ToString(args["key"])
		return d[key], nil
	})

	state.Command("del", func(data interface{}, args map[string]interface{}) (interface{}, error) {
		d := data.(map[string]string)
		key := cast.ToString(args["key"])
		value := d[key]
		delete(d, key)
		return value, nil
	})

	ctx, cancel := context.WithCancel(context.Background())
	go func() { logrus.Fatal(node.Start(ctx)) }()

	// http server
	app := fiber.New()
	app.Get("/:op/:key/:val?", func(c *fiber.Ctx) error {
		result, err := node.Apply(c.Params("op"), time.Second, "key", c.Params("key"), "val", c.Params("val"))
		if err != nil {
			return err
		}

		return c.SendString(cast.ToString(result))
	})

	go func() { logrus.Fatal(app.Listen(fmt.Sprintf(":%d", hport))) }()

	// waiting
	ctrlc.Watch(func() {
		cancel()
		app.Shutdown()
	})

	<-ctx.Done()
}

License

Copyright (c) 2021-present Daniel Gatis

Licensed under MIT License

Buy me a coffee

Liked some of my work? Buy me a coffee (or more likely a beer)

Buy Me A Coffee

Similar Resources

The source-code for: "Build a Blockchain from Scratch in Go" eBook.

The source-code for:

The Blockchain Bar The source-code for: "Build a Blockchain from Scratch in Go" eBook. 📚 Get the eBook from: https://gumroad.com/l/build-a-blockchain

Jan 2, 2023

Accompanying repository for the "Build Ethereum From Scratch - Smart Contracts and More" course by David Katz

Accompanying repository for the

Build Ethereum From Scratch - Smart Contracts and More This repository accompanies the "Build Ethereum From Scratch - Smart Contracts and More" course

Dec 7, 2022

Content and build toolchain for Zig by Example

Content and build toolchain for Zig by Example

Content and build toolchain for Zig by Example. Building To build the site you'll need Go installed. Run: tools/build To build continuously in a loop:

Dec 5, 2022

Berylbit PoW chain using Ethash, EPI-Burn and geth. The chain will be using bot congestion flashbot bundles through nodes

Berylbit PoW chain using Ethash, EPI-Burn and geth. The chain will be using bot congestion flashbot bundles through nodes. Soon, We will work towards

Jun 30, 2022

Easy to use cryptographic framework for data protection: secure messaging with forward secrecy and secure data storage. Has unified APIs across 14 platforms.

Easy to use cryptographic framework for data protection: secure messaging with forward secrecy and secure data storage. Has unified APIs across 14 platforms.

Themis provides strong, usable cryptography for busy people General purpose cryptographic library for storage and messaging for iOS (Swift, Obj-C), An

Jan 9, 2023

Trader is a framework that automated cryptocurrency exchange with strategy

Trader is a framework that automated cryptocurrency exchange with strategy

A framework that automated cryptocurrency exchange with strategy

Nov 29, 2022

Yu is a highly customizable blockchain framework.

Yu is a highly customizable blockchain framework.

禹 Yu is a highly customizable blockchain framework. 中文文档 Overall Structure Introduction By using Yu, you can customize three levels to develop your ow

Jan 7, 2023

Yu is a highly customizable blockchain framework.

Yu is a highly customizable blockchain framework.

禹 Yu is a highly customizable blockchain framework. 中文文档 Overall Structure Introduction By using Yu, you can customize three levels to develop your ow

Dec 11, 2022

Eunomia is a distributed application framework that support Gossip protocol, QuorumNWR algorithm, PBFT algorithm, PoW algorithm, and ZAB protocol and so on.

Introduction Eunomia is a distributed application framework that facilitates developers to quickly develop distributed applications and supports distr

Sep 28, 2021
Go language implementation of a blockchain based on the BDLS BFT protocol. The implementation was adapted from Ethereum and Sperax implementation

BDLS protocol based PoS Blockchain Most functionalities of this client is similar to the Ethereum golang implementation. If you do not find your quest

Oct 14, 2022
Fallback to build simdjson-go tape using only encoding/json

fakesimdjson builds a simdjson-go tape using the stdlib's JSON parser. It is slow and does a lot of allocations. This is a workaround to run programs

Mar 11, 2022
go-actor is a lightweight message framework using actor model

go-actor go-actor is a lightweight message framework using actor model 初衷 想能在代码逻辑上方便的写无锁的同步rpc调用代码,同时又不会阻塞住其他服务对这个Actor的调用 一个Actor可以有多种身份,想能比较方便的分类管理A

Oct 21, 2022
Implementation of blockchain using golang

go-blockchain Basic implementation of blockchain using golang. Initialize Blockc

Feb 18, 2022
Kava - Reference implementation of Kava, a blockchain for cross-chain DeFi. Built using the cosmos-sdk

DeFi for Crypto. Telegram | Medium | Discord Reference implementation of Kava, a

Apr 4, 2022
Build apps that run everywhere with Go and a browser engine of your choice (Chrome, Firefox, Epiphany or Android WebView).

hydrapp Build apps that run everywhere with Go and a browser engine of your choice (Chrome, Firefox, Epiphany or Android WebView). Overview ?? This pr

Dec 14, 2022
Build a circular sector polygon feature spanning the angle between two given bearings, a center point and a radius. A pizza piece! 🍕
Build a circular sector polygon feature spanning the angle between two given bearings, a center point and a radius. A pizza piece! 🍕

sectr ?? Build a circular sector polygon feature (pizza piece ?? ) spanning the angle between two given bearings, a radius and a center point. install

Oct 1, 2022
Build a local copy of Known Exploited Vulnerabilities Catalog by CISA. Server mode for easy querying.

go-kev go-kev build a local copy of Known Exploited Vulnerabilities Catalog by CISA. Usage $ go-kev help Go Known Exploited Vulnerabilities Usage:

Oct 30, 2022
Build a local copy of Known Exploited Vulnerabilities Catalog by CISA. Server mode for easy querying.

go-kev go-kev build a local copy of Known Exploited Vulnerabilities Catalog by CISA. Usage $ go-kev help Go Known Exploited Vulnerabilities Usage:

Oct 30, 2022
Build your own blockchain!
Build your own blockchain!

Build your own Blockchain in Javascript With all the hype about blockchains and cryptocurrencies, I decided to learn a bit more about it. And what bet

Dec 31, 2022