handle.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. package http
  2. import (
  3. "bytes"
  4. "context"
  5. json2 "encoding/json"
  6. "io/ioutil"
  7. "net/http"
  8. "strings"
  9. context2 "git.ikuban.com/server/kratos-utils/http/context"
  10. "google.golang.org/grpc/codes"
  11. status2 "google.golang.org/grpc/status"
  12. "github.com/go-kratos/kratos/v2/errors"
  13. "google.golang.org/protobuf/encoding/protojson"
  14. "github.com/go-kratos/kratos/v2/encoding"
  15. "google.golang.org/protobuf/types/known/emptypb"
  16. "git.ikuban.com/server/kratos-utils/http/binding"
  17. "git.ikuban.com/server/kratos-utils/http/encoding/json"
  18. _ "github.com/go-kratos/kratos/v2/encoding/proto"
  19. )
  20. // decodeRequest decodes the request body to object.
  21. func DecodeRequest(req *http.Request, v interface{}) error {
  22. method := strings.ToUpper(req.Method)
  23. if method == "POST" || method == "PUT" || method == "DELETE" {
  24. contextType := req.Header.Get(ContentTypeHeader)
  25. if strings.HasPrefix(contextType, "multipart/form-data") {
  26. return parseForm(req, v)
  27. }
  28. if _, ok := v.(*emptypb.Empty); ok {
  29. return binding.BindForm(req, v)
  30. }
  31. subtype := contentSubtype(contextType)
  32. if codec := encoding.GetCodec(subtype); codec != nil {
  33. data, err := ioutil.ReadAll(req.Body)
  34. if err != nil {
  35. return err
  36. }
  37. return codec.Unmarshal(data, v)
  38. }
  39. }
  40. return binding.BindForm(req, v)
  41. }
  42. func parseForm(req *http.Request, v interface{}) error {
  43. err := req.ParseMultipartForm(32 << 20)
  44. if err != nil {
  45. return err
  46. }
  47. if req.MultipartForm == nil {
  48. return nil
  49. }
  50. value := make(map[string]interface{})
  51. if req.MultipartForm.File != nil {
  52. for k1, v1 := range req.MultipartForm.File {
  53. f, err := v1[0].Open()
  54. if err != nil {
  55. return err
  56. }
  57. var buf bytes.Buffer
  58. _, err = buf.ReadFrom(f)
  59. if err != nil {
  60. return err
  61. }
  62. value[k1] = buf.Bytes()
  63. value[k1+"Filename"] = v1[0].Filename
  64. }
  65. }
  66. if req.MultipartForm.Value != nil {
  67. for k1, v1 := range req.MultipartForm.Value {
  68. value[k1] = v1[0]
  69. }
  70. }
  71. j, err := json2.Marshal(value)
  72. if err != nil {
  73. return err
  74. }
  75. err = json2.Unmarshal(j, v)
  76. return err
  77. }
  78. // encodeResponse encodes the object to the HTTP response.
  79. func EncodeResponse(w http.ResponseWriter, r *http.Request, v interface{}) error {
  80. codec := codecForRequest(r)
  81. data, err := codec.Marshal(v)
  82. if err != nil {
  83. return err
  84. }
  85. w.Header().Set(ContentTypeHeader, contentType(codec.Name()))
  86. _, _ = w.Write(data)
  87. return nil
  88. }
  89. func ErrHandle(w http.ResponseWriter, r *http.Request, err error) {
  90. st := errors.FromError(err)
  91. if st == nil {
  92. st = errors.New(10500, "", "", err.Error())
  93. }
  94. status := st.GRPCStatus()
  95. code := status.Proto().Code
  96. if code == 1000 {
  97. return
  98. }
  99. w.Header().Set(ContentTypeHeader, "application/json; charset=utf-8")
  100. if code == 0 {
  101. w.WriteHeader(200)
  102. } else if code >= 301 && code <= 307 {
  103. w.WriteHeader(int(code))
  104. http.Redirect(w, r, status.Message(), int(code))
  105. return
  106. } else if code == 401 {
  107. w.WriteHeader(401)
  108. status = status2.New(codes.Code(10401), status.Message())
  109. } else {
  110. if code < 10000 {
  111. code = 10000 + code
  112. }
  113. message := status.Message()
  114. if code < 10100 && status.Message() == "" {
  115. message = "系统错误"
  116. }
  117. status = status2.New(codes.Code(code), message)
  118. w.WriteHeader(400)
  119. }
  120. data, err := protojson.Marshal(status.Proto())
  121. if err != nil {
  122. w.WriteHeader(http.StatusInternalServerError)
  123. return
  124. }
  125. w.Write(data)
  126. //se := errors.FromError(err)
  127. //if !ok {
  128. // se = &errors.StatusError{
  129. // Code: 10500,
  130. // Message: err.Error(),
  131. // }
  132. //}
  133. //if se.Code == -1 {
  134. // return
  135. //}
  136. //codec := codecForRequest(r)
  137. //w.Header().Set(ContentTypeHeader, contentType(codec.Name()))
  138. //if se.Code == 0 {
  139. // w.WriteHeader(200)
  140. //} else if se.Code >= 301 && se.Code <= 307 {
  141. // w.WriteHeader(int(se.Code))
  142. // http.Redirect(w, r, se.Message, int(se.Code))
  143. // return
  144. //} else {
  145. // if se.Code < 10000 {
  146. // se.Code = 10000 + se.Code
  147. // }
  148. // if se.Code < 10100 && se.Message == "" {
  149. // se.Message = "系统错误"
  150. // }
  151. // w.WriteHeader(400)
  152. //}
  153. //data, _ := codec.Marshal(se)
  154. //_, _ = w.Write(data)
  155. }
  156. const baseContentType = "application"
  157. var (
  158. acceptHeader = http.CanonicalHeaderKey("Accept")
  159. ContentTypeHeader = http.CanonicalHeaderKey("Content-Type")
  160. )
  161. func contentType(subtype string) string {
  162. return strings.Join([]string{baseContentType, subtype}, "/")
  163. }
  164. // codecForRequest get encoding.Codec via http.Request
  165. func codecForRequest(r *http.Request) encoding.Codec {
  166. var codec encoding.Codec
  167. for _, accept := range r.Header[acceptHeader] {
  168. codeName := contentSubtype(accept)
  169. if codeName == "json" {
  170. codec = encoding.GetCodec(json.Name)
  171. break
  172. }
  173. if codec = encoding.GetCodec(codeName); codec != nil {
  174. break
  175. }
  176. }
  177. if codec == nil {
  178. codec = encoding.GetCodec(json.Name)
  179. }
  180. return codec
  181. }
  182. func contentSubtype(contentType string) string {
  183. if contentType == baseContentType {
  184. return ""
  185. }
  186. if !strings.HasPrefix(contentType, baseContentType) {
  187. return ""
  188. }
  189. switch contentType[len(baseContentType)] {
  190. case '/', ';':
  191. if i := strings.Index(contentType, ";"); i != -1 {
  192. return contentType[len(baseContentType)+1 : i]
  193. }
  194. return contentType[len(baseContentType)+1:]
  195. default:
  196. return ""
  197. }
  198. }
  199. func SetBody(ctx context.Context, r *http.Request) {
  200. b, _ := ioutil.ReadAll(r.Body)
  201. if len(b) > 0 {
  202. ctx = context2.AppendToContext(ctx, "body", b)
  203. }
  204. }