blest

package module
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 6, 2023 License: MIT Imports: 12 Imported by: 0

README

BLEST Go

The Go reference implementation of BLEST (Batch-able, Lightweight, Encrypted State Transfer), an improved communication protocol for web APIs which leverages JSON, supports request batching and selective returns, and provides a modern alternative to REST. It includes an example for Gin.

To learn more about BLEST, please visit the website: https://blest.jhunt.dev

For a front-end implementation in React, please visit https://github.com/jhuntdev/blest-react

Features

  • Built on JSON - Reduce parsing time and overhead
  • Request Batching - Save bandwidth and reduce load times
  • Compact Payloads - Save more bandwidth
  • Selective Returns - Save even more bandwidth
  • Single Endpoint - Reduce complexity and improve data privacy
  • Fully Encrypted - Improve data privacy

Installation

Install BLEST Go from Go Packages.

go get github.com/jhuntdev/blest-go

Usage

This default export of this library has an interface very similar to Gin. It also provides a Router struct with a Handle method for use in an existing NodeJS application and an HttpClient struct with a Request method for making BLEST HTTP requests.

package main

import "github.com/jhuntdev/blest-go"

// Create some middleware (optional)
func authMiddleware(params interface{}, context *map[string]interface{}) {
	name, ok := params.(map[string]interface{})["name"].(string)
	if !ok {
		return nil, errors.New("Unauthorized")
	}
	(*context)["user"] = map[string]interface{}{
		"name": name,
	}
}

// Create a route controller
func greetController(params interface{}, context *map[string]interface{}) (interface{}, error) {
	user, ok := (*context)["user"].(map[string]interface{})
	if !ok {
		return nil, errors.New("user not found or has an invalid type")
	}
	name, ok := user["name"].(string)
	if !ok {
		return nil, errors.New("name not found or has an invalid type")
	}
	greeting := fmt.Sprintf("Hi, %v!", name)
	return map[string]interface{}{
		"greeting": greeting,
	}, nil
}

func main() {
	r := blest.Default()
	r.Use(authMiddleware)
	r.Route("greet", greetController)
	r.Run() // listen and serve on 0.0.0.0:8080
}
Router
package main

import {
	"github.com/jhuntdev/blest-go"
	"github.com/gin-gonic/gin"
}

// Create some middleware (optional)
func authMiddleware(params interface{}, context *map[string]interface{}) {
	name, ok := params.(map[string]interface{})["name"].(string)
	if !ok {
		return nil, errors.New("Unauthorized")
	}
	(*context)["user"] = map[string]interface{}{
		"name": name,
	}
}

// Create a route controller
func greetController(params interface{}, context *map[string]interface{}) (interface{}, error) {
	user, ok := (*context)["user"].(map[string]interface{})
	if !ok {
		return nil, errors.New("user not found or has an invalid type")
	}
	name, ok := user["name"].(string)
	if !ok {
		return nil, errors.New("name not found or has an invalid type")
	}
	greeting := fmt.Sprintf("Hi, %v!", name)
	return map[string]interface{}{
		"greeting": greeting,
	}, nil
}

// Create your router
router := blest.Router()
router.Use(authMiddleware)
router.Route("greet", greetController)

func main() {
	r := gin.Default()
	r.POST("/", func(c *gin.Context) {
		var req gin.Request
		if err := c.ShouldBindJSON(&req); err != nil {
			c.JSON(400, gin.H{
				"error": "Invalid JSON payload",
			})
			return
		}
		// Use the router
		response, e := router.Handle(req.Data, nil)
		if e !== nil {
			c.JSON(500, e)
		} else {
			c.JSON(200, response)
		}
	})
	r.Run() // listen and serve on 0.0.0.0:8080
}
HttpClient
package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"log"

	"github.com/jhuntdev/blest-go"
)

func main() {
	// Set headers (optional)
	headers := map[string]string{
		"Authorization": "Bearer token",
	}

	// Create a client
	client := blest.NewHttpClient("http://localhost:8080", map[string]interface{}{"headers": headers})
	
	// Send a request
	result, err := client.Request("greet", map[string]interface{}{ "name": "Steve" }, []interface{}{ "greeting" })
	if err != nil {
		// Do something in case of error
	} else {
		// Do something with the result
	}
}

License

This project is licensed under the MIT License.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewBlestError added in v0.1.0

func NewBlestError(message string, args ...interface{}) error

func NewHttpServer added in v0.1.2

func NewHttpServer(requestHandler RequestHandler, args ...interface{}) *http.Server

Types

type BlestError added in v0.1.0

type BlestError struct {
	Message    string
	StatusCode int
	Code       string
}

func (*BlestError) Error added in v0.1.0

func (be *BlestError) Error() string

type HttpClient added in v0.1.0

type HttpClient struct {
	Url          string
	Options      map[string]interface{}
	Headers      map[string]string
	MaxBatchSize int
	Queue        [][]interface{}
	Timeout      *time.Timer
	Emitter      *EventEmitter
}

func NewHttpClient added in v0.1.0

func NewHttpClient(url string, args ...interface{}) *HttpClient

func (*HttpClient) Process added in v0.1.0

func (c *HttpClient) Process()

func (*HttpClient) Request added in v0.1.0

func (c *HttpClient) Request(route string, args ...interface{}) (map[string]interface{}, error)

type RequestHandler added in v0.1.0

type RequestHandler func(requests [][]interface{}, context map[string]interface{}) ([][4]interface{}, map[string]interface{})

type Route added in v0.1.0

type Route struct {
	Handler     []interface{}
	Description string
	Parameters  interface{}
	Result      interface{}
	Visible     bool
	Validate    bool
	Timeout     int
}

type Router added in v0.1.0

type Router struct {
	Options       map[string]interface{}
	Introspection bool
	Middleware    []interface{}
	Afterware     []interface{}
	Timeout       int
	Routes        map[string]Route
}

func Default added in v0.1.0

func Default(options map[string]interface{}) *Router

func NewRouter added in v0.1.0

func NewRouter(args ...interface{}) *Router

func (*Router) Describe added in v0.1.0

func (r *Router) Describe(route string, config map[string]interface{}) error

func (*Router) Handle added in v0.1.0

func (r *Router) Handle(requests [][]interface{}, context map[string]interface{}) ([][4]interface{}, map[string]interface{})

func (*Router) Merge added in v0.1.0

func (r *Router) Merge(router *Router) error

func (*Router) Namespace added in v0.1.0

func (r *Router) Namespace(prefix string, router *Router) error

func (*Router) Route added in v0.1.0

func (r *Router) Route(route string, args ...interface{})

func (*Router) Run added in v0.1.0

func (r *Router) Run()

func (*Router) Use added in v0.1.0

func (r *Router) Use(handlers ...interface{})

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL