- Simple, Poetic, Pithy.
- No
reflect
package.- But
reflect
package is used only when invoke the debug handler.
- But
- Support both packages
context
andgolang.org/x/net/context
. - Support GAE/Go Standard Environment.
- Compliance with JSON-RPC 2.0.
$ go get -u github.com/osamingo/jsonrpc
package main
import (
"context"
"encoding/json"
"log"
"net/http"
"github.com/osamingo/jsonrpc"
)
type (
EchoHandler struct {}
EchoParams struct {
Name string `json:"name"`
}
EchoResult struct {
Message string `json:"message"`
}
)
var _ (jsonrpc.Handler) = (*EchoHandler)(nil)
func (h *EchoHandler)ServeJSONRPC(c context.Context, params *json.RawMessage) (interface{}, *jsonrpc.Error) {
var p EchoParams
if err := jsonrpc.Unmarshal(params, &p); err != nil {
return nil, err
}
return EchoResult{
Message: "Hello, " + p.Name,
}, nil
}
func init() {
jsonrpc.RegisterMethod("Main.Echo", &EchoHandler{}, EchoParams{}, EchoResult{})
}
func main() {
http.HandleFunc("/jrpc", jsonrpc.HandlerFunc)
http.HandleFunc("/jrpc/debug", jsonrpc.DebugHandlerFunc)
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatalln(err)
}
}
POST /jrpc HTTP/1.1
Accept: application/json, */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 82
Content-Type: application/json
Host: localhost:8080
User-Agent: HTTPie/0.9.6
{
"jsonrpc": "2.0",
"method": "Main.Echo",
"params": {
"name": "John Doe"
},
"id": "243a718a-2ebb-4e32-8cc8-210c39e8a14b"
}
HTTP/1.1 200 OK
Content-Length: 68
Content-Type: application/json
Date: Mon, 28 Nov 2016 13:48:13 GMT
{
"jsonrpc": "2.0",
"result": {
"message": "Hello, John Doe"
},
"id": "243a718a-2ebb-4e32-8cc8-210c39e8a14b"
}
GET /jrpc/debug HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Host: localhost:8080
User-Agent: HTTPie/0.9.6
HTTP/1.1 200 OK
Content-Length: 408
Content-Type: application/json
Date: Mon, 28 Nov 2016 13:56:24 GMT
[
{
"handler": "EchoHandler",
"name": "Main.Echo",
"params": {
"$ref": "#/definitions/EchoParams",
"$schema": "http://json-schema.org/draft-04/schema#",
"definitions": {
"EchoParams": {
"additionalProperties": false,
"properties": {
"name": {
"type": "string"
}
},
"required": [
"name"
],
"type": "object"
}
}
},
"result": {
"$ref": "#/definitions/EchoResult",
"$schema": "http://json-schema.org/draft-04/schema#",
"definitions": {
"EchoResult": {
"additionalProperties": false,
"properties": {
"message": {
"type": "string"
}
},
"required": [
"message"
],
"type": "object"
}
}
}
}
]
Released under the MIT License.