Git Product home page Git Product logo

zenrpc's Introduction

zenrpc: JSON-RPC 2.0 Server Implementation with SMD support

Go Report Card Build Status codecov GoDoc

zenrpc is a JSON-RPC 2.0 server library with Service Mapping Description support. It's built on top of go generate instead of reflection.

How to Use

Service is struct with RPC methods, service represents RPC namespace.

  1. Install zenrpc generator go get github.com/semrush/zenrpc/v2/zenrpc
  2. Import github.com/semrush/zenrpc/v2 into our code with rpc service.
  3. Add trailing comment //zenrpc to your service or embed zenrpc.Service into your service struct.
  4. Write your funcs almost as usual.
  5. Do not forget run go generate or zenrpc for magic

Accepted Method Signatures

func(Service) Method([args]) (<value>, <error>)
func(Service) Method([args]) <value>
func(Service) Method([args]) <error>
func(Service) Method([args])
  • Value could be a pointer
  • Error is error or *zenrpc.Error

Example

package main

import (
	"flag"
	"context"
	"errors"
	"math"
	"log"
	"net/http"
	"os"	
	
	"github.com/semrush/zenrpc/v2"
	"github.com/semrush/zenrpc/v2/testdata"
)

type ArithService struct{ zenrpc.Service }

// Sum sums two digits and returns error with error code as result and IP from context.
func (as ArithService) Sum(ctx context.Context, a, b int) (bool, *zenrpc.Error) {
	r, _ := zenrpc.RequestFromContext(ctx)

	return true, zenrpc.NewStringError(a+b, r.Host)
}

// Multiply multiples two digits and returns result.
func (as ArithService) Multiply(a, b int) int {
	return a * b
}

type Quotient struct {
	Quo, Rem int
}

func (as ArithService) Divide(a, b int) (quo *Quotient, err error) {
	if b == 0 {
		return nil, errors.New("divide by zero")
	} else if b == 1 {
		return nil, zenrpc.NewError(401, errors.New("we do not serve 1"))
	}

	return &Quotient{
		Quo: a / b,
		Rem: a % b,
	}, nil
}

// Pow returns x**y, the base-x exponential of y. If Exp is not set then default value is 2.
//zenrpc:exp=2
func (as ArithService) Pow(base float64, exp float64) float64 {
	return math.Pow(base, exp)
}

//go:generate zenrpc

func main() {
	addr := flag.String("addr", "localhost:9999", "listen address")
	flag.Parse()

	rpc := zenrpc.NewServer(zenrpc.Options{ExposeSMD: true})
	rpc.Register("arith", testdata.ArithService{})
	rpc.Register("", testdata.ArithService{}) // public
	rpc.Use(zenrpc.Logger(log.New(os.Stderr, "", log.LstdFlags)))

	http.Handle("/", rpc)

	log.Printf("starting arithsrv on %s", *addr)
	log.Fatal(http.ListenAndServe(*addr, nil))
}

Magic comments

All comments are optional.

Method comments
//zenrpc:<method parameter>[=<default value>][whitespaces<description>]
//zenrpc:<error code>[whitespaces<description>]
//zenrpc:return[whitespaces<description>]
 
Struct comments
type MyService struct {} //zenrpc

Need to browse your api and do some test api calls?

We recommend to use SMDBox. It is Swagger-like JSON RPC API browser, compatible with smd scheme, generated by zenrpc.

JSON-RPC 2.0 Supported Features

  • Requests
    • Single requests
    • Batch requests
    • Notifications
  • Parameters
    • Named
    • Position
    • Default values
  • SMD Schema
    • Input
    • Output
    • Codes
    • Scopes for OAuth

Server Library Features

  • go generate
  • Transports
    • HTTP
    • WebSocket
    • RabbitMQ
  • Server middleware
    • Basic support
    • Metrics
    • Logging

zenrpc's People

Contributors

green13 avatar sergeyfast avatar dizzyfool avatar mikhail-eremin avatar shuler avatar playboyko avatar s3rj1k avatar dvrkps avatar ehsanranjbar avatar vetcher avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.