前端框架选型是企业提升开发效率与用户体验的关键因素
822
2022-10-28
一个用于编写jsON-RPC Web应用的微框架
jsonrpc-go
Package jsonrpc implements a microframework for writing JSON-RPC web applications.
Methods
Methods are defined as:
func(ctx context.Context, params T) (interface{}, error) // JSON unmarshable paramsfunc(ctx context.Context) (interface{}, error) // no params
where T can be any time which can be unmarshaled from JSON (structs and primitives).
If a method returns a value along with a nil error, the value will be rendered to the client as JSON.
If an error is returned, it will be sanitized and returned to the client as json. Errors generated by a call to jsonrpc.Error(name, message, args) will be rendered as-is to the client. Any other errors will be obfuscated to the caller (unless server.DumpErrors is enabled).
Spec
jsonrpc loosely follows the JSON-RPC 2.0 Specification, with some notable differences:
the version parameter is not expected, and will not be returnederrors include a Name string, rather than an integer Code
Example
var logger = log.New(os.Stderr, "server: ", 0)func main() { server := jsonrpc.New() server.Use(LoggingMiddleware(logger)) server.Register(jsonrpc.Methods{ "Hello": hello, }) http.ListenAndServe(":80", server)}type helloParams struct { Name string `json:"name"`}func hello(ctx context.Context, params *helloParams) (interface{}, error) { return jsonrpc.M{"message": fmt.Sprintf("Hello, %s", params.Name)}, nil}func LoggingMiddleware(logger *logger.Logger) Middleware { return func (next jsonrpc.Next) jsonrpc.Next { return func(ctx context.Context, params interface{}) (interface{}, error) { method := jsonrpc.MethodFromContext(ctx) start := time.Now() defer func() { logger.Printf("%s (%v)\n", method, time.Since(start)) }() return next(ctx, params) } }}
Request:
{ "id": 1, "method": "Hello", "params": { "name": "Alice" }}
Response:
{ "id": 1, "result": { "message": "Hello, Alice!" }}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~