使用fasthttp比较多,号码助手 app 过滤接口使用的fastjson解析数据,弄了一个利用quicktemplate输出 jsonrpc数据 的小代码。
速度不错,完整代码在 https://github.com/zc310/fastjsonrpc
$ GOMAXPROCS=1 go test -bench=. -benchmem
BenchmarkEchoHandler 3288985 369.6 ns/op 0 B/op 0 allocs/op
BenchmarkSumHandler 2464785 487.4 ns/op 0 B/op 0 allocs/op
BenchmarkErrorHandler 2052237 571.6 ns/op 48 B/op 1 allocs/op
BenchmarkBatchSumHandler 884662 1368 ns/op 712 B/op 11 allocs/op实例 #
package main
import (
"errors"
"github.com/zc310/fastjsonrpc"
"log"
"github.com/fasthttp/router"
"github.com/valyala/fasthttp"
)
func Index(ctx *fasthttp.RequestCtx) {
_, _ = ctx.WriteString("Hello, world!")
}
func main() {
r := router.New()
r.GET("/", Index)
var ss fastjsonrpc.ServerMap
var tt Arith
_ = ss.Register(&tt)
ss.RegisterHandler("echo", func(c *fastjsonrpc.Context) {
c.Result = c.Params
})
r.POST("/rpc", fasthttp.CompressHandler(ss.Handler))
r.POST("/handler", fastjsonrpc.Rpc(handler))
log.Fatal(fasthttp.ListenAndServe(":8080", r.Handler))
}
type Arith int
func (t *Arith) Add(c *fastjsonrpc.Context) {
c.Result = c.Arena.NewNumberInt(c.Params.GetInt("a") + c.Params.GetInt("b"))
}
func (t *Arith) Mul(c *fastjsonrpc.Context) {
c.Result = c.Arena.NewNumberInt(c.Params.GetInt("a") * c.Params.GetInt("b"))
}
func (t *Arith) Div(c *fastjsonrpc.Context) {
if c.Params.GetInt("b") == 0 {
c.Error = errors.New("divide by zero")
return
}
c.Result = c.Arena.NewNumberInt(c.Params.GetInt("a") / c.Params.GetInt("b"))
}
func (t *Arith) Panic(*fastjsonrpc.Context) { panic("ERROR") }
func (t *Arith) Error(c *fastjsonrpc.Context) { c.Error = fastjsonrpc.NewError(0, "123") }
func handler(c *fastjsonrpc.Context) {
c.Result = c.Arena.NewNumberInt(c.Params.GetInt("a") + c.Params.GetInt("b"))
}HTTP Request #
### echo
POST http://localhost:8080/rpc
Content-Type: application/json
{"jsonrpc":"2.0","method":"echo","params":{"a":9,"b":9},"id":9}
### sum
POST http://localhost:8080/rpc
Content-Type: application/json
{"jsonrpc":"2.0","method":"sum","params":{"a":9,"b":9},"id":9}
### Arith.Add
POST http://localhost:8080/rpc
Content-Type: application/json
{"jsonrpc":"2.0","method":"Arith.Add","params":{"a":9,"b":9},"id":9}
### Arith.Mul
POST http://localhost:8080/rpc
Content-Type: application/json
{"jsonrpc":"2.0","method":"Arith.Mul","params":{"a":9,"b":9},"id":9}
### Arith.Div
POST http://localhost:8080/rpc
Content-Type: application/json
{"jsonrpc":"2.0","method":"Arith.Div","params":{"a":9,"b":9},"id":9}
### Arith.Error
POST http://localhost:8080/rpc
Content-Type: application/json
{"jsonrpc":"2.0","method":"Arith.Error","params":{"a":9,"b":9},"id":9}
### Arith.Panic
POST http://localhost:8080/rpc
Content-Type: application/json
{"jsonrpc":"2.0","method":"Arith.Panic","params":{"a":9,"b":9},"id":9}