github.com/volts-dev/volts@v0.0.0-20240120094013-5e9c65924106/transport/http_request.go (about) 1 package transport 2 3 import ( 4 "io/ioutil" 5 "net/http" 6 "strings" 7 8 "github.com/volts-dev/volts/codec" 9 "github.com/volts-dev/volts/internal/body" 10 "github.com/volts-dev/volts/logger" 11 ) 12 13 type ( 14 THttpRequest struct { 15 *http.Request 16 Transport ITransport 17 body *body.TBody // 18 codec codec.ICodec 19 } 20 ) 21 22 // 提供给Router的context使用 23 func NewHttpRequest(req *http.Request) *THttpRequest { 24 r := &THttpRequest{ 25 Request: req, 26 } 27 28 r.body = body.New(r.Codec()) 29 return r 30 } 31 32 func (self *THttpRequest) Codec() codec.ICodec { 33 if self.codec == nil { 34 ct := self.Request.Header.Get("Content-Type") 35 ct = strings.Split(ct, ";")[0] // 分割“application/json;charset=UTF-8” 36 // TODO 添加更多 37 var st codec.SerializeType 38 switch ct { 39 case "application/json": 40 st = codec.JSON 41 default: 42 st = codec.Use(ct) 43 } 44 self.codec = codec.IdentifyCodec(st) 45 } 46 47 return self.codec 48 } 49 50 func (self *THttpRequest) Body() *body.TBody { 51 if self.body.Data.Len() == 0 { 52 data, err := ioutil.ReadAll(self.Request.Body) 53 if err != nil { 54 logger.Errf("Read request body faild with an error : %s!", err.Error()) 55 } 56 57 self.body.Data.Write(data) 58 } 59 60 return self.body 61 } 62 63 func (self *THttpRequest) Interface() interface{} { 64 return self.Request 65 } 66 67 func (self *THttpRequest) ____Method() string { 68 return self.Request.Method 69 } 70 71 func (self *THttpRequest) ____ContentType() string { 72 return self.Request.Header.Get("Content-Type") 73 } 74 75 // Header of the request 76 func (self *THttpRequest) Header() http.Header { 77 return self.Request.Header 78 } 79 80 // Body is the initial decoded value 81 // Body() interface{} 82 // Read the undecoded request body 83 func (self *THttpRequest) Read() ([]byte, error) { return nil, nil } 84 85 // The encoded message stream 86 // Codec() codec.Reader 87 // Indicates whether its a stream 88 func (self *THttpRequest) Stream() bool { 89 return false 90 }