http.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "net/url"
  8. "strings"
  9. "go-common/library/ecode"
  10. bm "go-common/library/net/http/blademaster"
  11. )
  12. var jsonFormat = "application/json; charset=utf-8"
  13. func splitURL(url string) (addr, path string, err error) {
  14. arrs := strings.Split(url, "/")
  15. if len(arrs) < 3 {
  16. err = ecode.RequestErr
  17. return
  18. }
  19. addr = arrs[1]
  20. path = fmt.Sprintf("/%s", strings.Join(arrs[2:], "/"))
  21. return
  22. }
  23. func formatRequest(req url.Values) (res map[string]interface{}) {
  24. res = map[string]interface{}{}
  25. for k, v := range req {
  26. value := v[0]
  27. res[k] = value
  28. // 支持数组
  29. if len(value) > 2 && value[0] == '[' && value[len(value)-1] == ']' {
  30. value = value[1 : len(value)-1]
  31. res[k] = strings.Split(value, ",")
  32. }
  33. }
  34. return
  35. }
  36. func handle(c *bm.Context) {
  37. addr, path, err := splitURL(c.Request.URL.Path)
  38. if err != nil {
  39. c.JSON(nil, ecode.RequestErr)
  40. return
  41. }
  42. var body []byte
  43. body, _ = ioutil.ReadAll(c.Request.Body)
  44. if len(body) == 0 || string(body) == "{}" {
  45. data := formatRequest(c.Request.Form)
  46. body, err = json.Marshal(data)
  47. if err != nil {
  48. c.JSONMap(map[string]interface{}{"message": err.Error()}, err)
  49. return
  50. }
  51. }
  52. resp, err := callGrpc(addr, path, body)
  53. if err != nil {
  54. var intro string
  55. if strings.Contains(err.Error(), "error unmarshalling request") {
  56. intro = "由于params都是string没有类型信息 如果含有int/int32等类型 请复制\"请求数据\"到body中 并修改请求的字段类型, 注意Content-Type 不能为 multipart/form-data 不然body无效 还有问题@wangxu01"
  57. }
  58. c.JSONMap(map[string]interface{}{
  59. "错误": err.Error(),
  60. "请求目标": addr,
  61. "请求方法": path,
  62. "请求数据": string(body),
  63. "额外说明": intro,
  64. }, err)
  65. return
  66. }
  67. c.Bytes(http.StatusOK, jsonFormat, resp)
  68. }