使用fasthttp比较多,号码助手 app 过滤接口使用的fastjson解析数据,弄了一个利用quicktemplate输出 jsonrpc数据 的小代码。
速度不错,完整代码在 https://github.com/zc310/fastjsonrpc
1$ GOMAXPROCS=1 go test -bench=. -benchmem
2
3BenchmarkEchoHandler 3288985 369.6 ns/op 0 B/op 0 allocs/op
4BenchmarkSumHandler 2464785 487.4 ns/op 0 B/op 0 allocs/op
5BenchmarkErrorHandler 2052237 571.6 ns/op 48 B/op 1 allocs/op
6BenchmarkBatchSumHandler 884662 1368 ns/op 712 B/op 11 allocs/op
实例
1package main
2
3import (
4 "errors"
5 "github.com/zc310/fastjsonrpc"
6 "log"
7
8 "github.com/fasthttp/router"
9 "github.com/valyala/fasthttp"
10)
11
12func Index(ctx *fasthttp.RequestCtx) {
13 _, _ = ctx.WriteString("Hello, world!")
14}
15
16func main() {
17 r := router.New()
18 r.GET("/", Index)
19
20 var ss fastjsonrpc.ServerMap
21
22 var tt Arith
23 _ = ss.Register(&tt)
24 ss.RegisterHandler("echo", func(c *fastjsonrpc.Context) {
25 c.Result = c.Params
26 })
27 r.POST("/rpc", fasthttp.CompressHandler(ss.Handler))
28 r.POST("/handler", fastjsonrpc.Rpc(handler))
29
30 log.Fatal(fasthttp.ListenAndServe(":8080", r.Handler))
31}
32
33type Arith int
34
35func (t *Arith) Add(c *fastjsonrpc.Context) {
36 c.Result = c.Arena.NewNumberInt(c.Params.GetInt("a") + c.Params.GetInt("b"))
37}
38
39func (t *Arith) Mul(c *fastjsonrpc.Context) {
40 c.Result = c.Arena.NewNumberInt(c.Params.GetInt("a") * c.Params.GetInt("b"))
41}
42
43func (t *Arith) Div(c *fastjsonrpc.Context) {
44 if c.Params.GetInt("b") == 0 {
45 c.Error = errors.New("divide by zero")
46 return
47 }
48 c.Result = c.Arena.NewNumberInt(c.Params.GetInt("a") / c.Params.GetInt("b"))
49}
50func (t *Arith) Panic(*fastjsonrpc.Context) { panic("ERROR") }
51func (t *Arith) Error(c *fastjsonrpc.Context) { c.Error = fastjsonrpc.NewError(0, "123") }
52func handler(c *fastjsonrpc.Context) {
53 c.Result = c.Arena.NewNumberInt(c.Params.GetInt("a") + c.Params.GetInt("b"))
54}
HTTP Request
1### echo
2
3POST http://localhost:8080/rpc
4Content-Type: application/json
5
6{"jsonrpc":"2.0","method":"echo","params":{"a":9,"b":9},"id":9}
7
8### sum
9
10POST http://localhost:8080/rpc
11Content-Type: application/json
12
13{"jsonrpc":"2.0","method":"sum","params":{"a":9,"b":9},"id":9}
14
15### Arith.Add
16
17POST http://localhost:8080/rpc
18Content-Type: application/json
19
20{"jsonrpc":"2.0","method":"Arith.Add","params":{"a":9,"b":9},"id":9}
21
22### Arith.Mul
23
24POST http://localhost:8080/rpc
25Content-Type: application/json
26
27{"jsonrpc":"2.0","method":"Arith.Mul","params":{"a":9,"b":9},"id":9}
28
29### Arith.Div
30
31POST http://localhost:8080/rpc
32Content-Type: application/json
33
34{"jsonrpc":"2.0","method":"Arith.Div","params":{"a":9,"b":9},"id":9}
35
36### Arith.Error
37
38POST http://localhost:8080/rpc
39Content-Type: application/json
40
41{"jsonrpc":"2.0","method":"Arith.Error","params":{"a":9,"b":9},"id":9}
42
43### Arith.Panic
44
45POST http://localhost:8080/rpc
46Content-Type: application/json
47
48{"jsonrpc":"2.0","method":"Arith.Panic","params":{"a":9,"b":9},"id":9}