j2rpc

package module
v0.0.0-...-0ee009f Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2023 License: Apache-2.0 Imports: 15 Imported by: 2

README

j2rpc

go jsonrpc framework

install

go get -u github.com/glibtools/j2rpc

usage

package main

import (
    "log"
    "net/http"
    "time"

    "github.com/glibtools/j2rpc"
)

func main() {
    rpc := j2rpc.NewServer(
        j2rpc.WithCallerAfterReadBody(func(bytes []byte) ([]byte, error) {
            log.Printf("read body: %s\n", string(bytes))
            return bytes, nil
        }),
        j2rpc.WithCallerBeforeWrite(func(bytes []byte) ([]byte, error) {
            log.Printf("write body: %s\n", string(bytes))
            return bytes, nil
        }),
    )
    rpc.Use("", loggerHandler())
    rpc.Use("", j2rpc.Recover())
    rpc.RegisterTypeBus(new(apiBus))
    mux := http.NewServeMux()
    mux.Handle("/rpc", rpc)
    log.Fatalln(http.ListenAndServe(":8080", mux))
}

type api struct{}

func (*api) Add(a, b int) int {
    return a + b
}

func (*api) Client(c j2rpc.Context) interface{} {
    return map[string]interface{}{
        "ip":     c.Request().RemoteAddr,
        "header": c.Request().Header,
    }
}

func (*api) Empty() {}

func (*api) Ping() string {
    return "pong"
}

type apiBus struct {
    API *api `j2rpc:"open"`
}

func loggerHandler() j2rpc.Handler {
    return func(ctx j2rpc.Context) {
        t1 := time.Now()
        ctx.Next()
        log.Printf("time cost: %s\n", time.Since(t1))
    }
}

Documentation

Index

Constants

View Source
const (
	BodyContextKey      = "___j2rpc.body"
	TimeBeginContextKey = "___j2rpc.timeBegin"
)
View Source
const Separator = "."

Variables

View Source
var MethodNameProvider = func(name string) string {

	return strings.ToLower(name[:1]) + name[1:]
}

Functions

func IndirectValue

func IndirectValue(val reflect.Value) reflect.Value

func JSONDecode

func JSONDecode(data []byte, v interface{}) error

func JSONEncode

func JSONEncode(v interface{}) ([]byte, error)

func ZeroValue

func ZeroValue(typ reflect.Type) reflect.Value

Types

type CallerBody

type CallerBody func([]byte) ([]byte, error)

type Context

type Context interface {
	context.Context
	Abort()
	AddHandler(handlers ...Handler)
	GetContext() context.Context
	GetValue(key string) (interface{}, bool)
	IsAbort() bool
	Msg() *RPCMessage
	Next()
	Request() *http.Request
	Server() Server
	SetValue(key string, val interface{})
	Writer() http.ResponseWriter
	StopWriteStringStatus(status int, str string)
	WriteResponse(args ...interface{})
	Wrote() bool
}

func NewContext

func NewContext(ctx context.Context, writer http.ResponseWriter, req *http.Request) Context

type Decoder

type Decoder = json.Decoder

func NewDecoder

func NewDecoder(r io.Reader) *Decoder

type Delim

type Delim = json.Delim

type Encoder

type Encoder = json.Encoder

func NewEncoder

func NewEncoder(w io.Writer) *Encoder

type Error

type Error struct {
	Code    ErrorCode   `json:"code"`
	Message string      `json:"message,omitempty"`
	Data    interface{} `json:"data,omitempty"`
}

Error ... Error codes

func NewError

func NewError(code ErrorCode, Msg string, data ...interface{}) *Error

NewError ...

func (*Error) Error

func (e *Error) Error() string

func (*Error) ErrorCode

func (e *Error) ErrorCode() int

func (*Error) ErrorData

func (e *Error) ErrorData() interface{}

type ErrorCode

type ErrorCode int

ErrorCode ... Error codes

const (
	ErrParse          ErrorCode = -32700
	ErrInvalidRequest ErrorCode = -32600
	ErrNoMethod       ErrorCode = -32601
	ErrBadParams      ErrorCode = -32602
	ErrInternal       ErrorCode = -32603
	ErrServer         ErrorCode = -32000

	ErrAuthorization ErrorCode = 401
	ErrForbidden     ErrorCode = 403
)

type Group

type Group interface {
	Handlers() []Handler
	Use(handlers ...Handler) Group
}

func NewGroup

func NewGroup(path string) Group

type Handler

type Handler func(c Context)

func Recover

func Recover() Handler

type ImplRPCMethodProvider

type ImplRPCMethodProvider interface {
	RPCMethodProvider(methodName string) string
}

type ImplRPCTypeName

type ImplRPCTypeName interface {
	RPCTypeName() string
}

type ItfJ2rpcError

type ItfJ2rpcError interface {
	ErrorCode() int
	Error() string
	ErrorData() interface{}
}

type Option

type Option func(option *ServerOption)

func WithCallerAfterReadBody

func WithCallerAfterReadBody(fn CallerBody) Option

func WithCallerBeforeWrite

func WithCallerBeforeWrite(fn CallerBody) Option

type RPCMessage

type RPCMessage struct {
	ID      RawMessage `json:"id,omitempty"`
	Version string     `json:"jsonrpc,omitempty"`
	Method  string     `json:"method,omitempty"`
	Params  RawMessage `json:"params,omitempty"`
	Result  RawMessage `json:"result,omitempty"`
	Error   *Error     `json:"error,omitempty"`
}

type RawMessage

type RawMessage = json.RawMessage

type Server

type Server interface {
	Handler(c Context)
	Option() *ServerOption
	RegisterFunc(args ...interface{})
	RegisterType(args ...interface{})
	RegisterTypeBus(bus interface{})
	ServeHTTP(writer http.ResponseWriter, request *http.Request)
	Use(path string, handlers ...Handler) Group
}

func NewServer

func NewServer(opt ...Option) Server

type ServerOption

type ServerOption struct {
	CallerAfterReadBody CallerBody
	CallerBeforeWrite   CallerBody
}

Jump to

Keyboard shortcuts

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