handle.go 5.3 KB

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