package module
Version: v0.0.0-...-c5d2208 Latest Latest

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

Go to latest
Published: Mar 1, 2018 License: BSD-3-Clause Imports: 9 Imported by: 0


Golang Jsonrpc 2.0 Package

Modified from Gorilla rpc & json2

  • Add middlewares support.
  • Use user-defined Context instead of http.Request
package main

import (

const MyToken = "MyToken"

type Context struct {
	AuthToken string

type MyService struct{}

func (*MyService) Hello(ctx *Context, args *struct {
	Text string
}, reply *struct {
	Text string
}) error {
	if ctx.AuthToken != MyToken {
		return fmt.Errorf("authorization fail")
	reply.Text = args.Text + "!"
	return nil

func FetchAuthToken(r *http.Request, ctx *Context) error {
	ctx.AuthToken = r.Header.Get("Authorization")
	return nil

func Logger(r *http.Request, ctx *Context) error {
	log.Println("log test")
	return nil

func main() {
	server, err := rpc.NewServer(new(Context))
	if err != nil {
	server.RegisterCodec(json.NewCodec(), "application/json")
	server.RegisterService(new(MyService), "")
	server.RegisterService(new(MyService), "Second")

	reqBody, _ := json.EncodeClientRequest("MyService.Hello", &struct{ Text string }{"Hello Rpc"})
	req := httptest.NewRequest("POST", "/", bytes.NewBuffer(reqBody))
	req.Header.Set("Authorization", MyToken)
	w := httptest.NewRecorder()
	server.ServeHTTP(w, req)
	resp := w.Result()
	reply := &struct{ Text string }{}
	if err := json.DecodeClientResponse(resp.Body, reply); err != nil {
	} else {





This section is empty.


View Source
var DefaultEncoder = &encoder{}
View Source
var DefaultEncoderSelector = &encoderSelector{}


func WriteError

func WriteError(w http.ResponseWriter, status int, msg string)

WriteError, a helper function to write error message to ResponseWriter


type Codec

type Codec interface {
	NewRequest(*http.Request) CodecRequest

Codec creates a CodecRequest to process each request.

type CodecRequest

type CodecRequest interface {
	// Reads the request and returns the RPC method name.
	Method() (string, error)
	// Reads the request filling the RPC method args.
	ReadRequest(interface{}) error
	// Writes the response using the RPC method reply.
	WriteResponse(http.ResponseWriter, interface{})
	// Writes an error produced by the server.
	WriteError(w http.ResponseWriter, status int, err error)

CodecRequest decodes a request and encodes a response using a specific serialization scheme.

type CompressionSelector

type CompressionSelector struct {

CompressionSelector generates the compressed http encoder.

func (*CompressionSelector) Select

func (_ *CompressionSelector) Select(r *http.Request) Encoder

Select method selects the correct compression encoder based on http HEADER.

type Encoder

type Encoder interface {
	Encode(w http.ResponseWriter) io.Writer

Encoder interface contains the encoder for http response. Eg. gzip, flate compressions.

type EncoderSelector

type EncoderSelector interface {
	Select(r *http.Request) Encoder

EncoderSelector interface provides a way to select encoder using the http request. Typically people can use this to check HEADER of the request and figure out client capabilities. Eg. "Accept-Encoding" tells about supported compressions.

type Server

type Server struct {
	// contains filtered or unexported fields

serves registered services with registered codecs.

func NewServer

func NewServer(ctx interface{}) (*Server, error)

NewServer returns a new RPC server. param ctx is non-nil, and used to restrict the context param for service registering

func (*Server) HasMethod

func (s *Server) HasMethod(name string) bool

HasMethod returns true if the given method is registered.

The method uses a dotted notation as in "Service.Method".

func (*Server) RegisterAfterFunc

func (s *Server) RegisterAfterFunc(fn interface{}) error

RegisterAfterFunc validate and add a func that will be executed after service call

func (*Server) RegisterBeforeFunc

func (s *Server) RegisterBeforeFunc(fn interface{}) error

RegisterBeforeFunc validate and add a func that will be executed before service call

func (*Server) RegisterCodec

func (s *Server) RegisterCodec(codec Codec, contentType string)

RegisterCodec adds a new codec to the server.

Codecs are defined to process a given serialization scheme, e.g., JSON or XML. A codec is chosen based on the "Content-Type" header from the request, excluding the charset definition.

func (*Server) RegisterService

func (s *Server) RegisterService(receiver interface{}, name string) error

RegisterService adds a new service to the server.

The name parameter is optional: if empty it will be inferred from the receiver type name.

Methods from the receiver will be extracted if these rules are satisfied:

- The receiver is exported (begins with an upper case letter) or local

(defined in the package registering the service).

- The method name is exported. - The method has three arguments: *[Context Type], *args, *reply. - All three arguments are pointers. - The second and third arguments are exported or local. - The method has return type error.

All other methods are ignored.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)


func (*Server) ServiceMap

func (s *Server) ServiceMap() map[string][]string

return the map of names of services with its methods


Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL