以下是优化读取请求的简化代码:
- package adapter
-
- import (
- "bytes"
- "io"
- "net/http"
- "sync"
-
- "github.com/json-iterator/go"
- "github.com/sirupsen/logrus"
- "github.com/thinkeridea/go-extend/exbytes"
- )
-
- type Adapter struct {
- pool sync.Pool
- }
-
- func New() *Adapter {
- return &Adapter{
- pool: sync.Pool{
- New: func() interface{} {
- return bytes.NewBuffer(make([]byte, 4096))
- },
- },
- }
- }
-
- func (api *Adapter) GetRequest(r *http.Request) (*Request, error) {
- buffer := api.pool.Get().(*bytes.Buffer)
- buffer.Reset()
- defer func() {
- if buffer != nil {
- api.pool.Put(buffer)
- buffer = nil
- }
- }()
-
- _, err := io.Copy(buffer, r.Body)
- if err != nil {
- return nil, err
- }
-
- request := &Request{}
- if err = jsoniter.Unmarshal(buffer.Bytes(), request); err != nil {
- logrus.WithFields(logrus.Fields{
- "json": exbytes.ToString(buffer.Bytes()),
- }).Errorf("jsoniter.UnmarshalJSON fail. error:%v", err)
- return nil, err
- }
- api.pool.Put(buffer)
- buffer = nil
-
- // ....
-
- return request, nil
- }
(编辑:西安站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|