common.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package common
  2. import (
  3. "mtp2_if/global/app"
  4. "mtp2_if/global/e"
  5. "mtp2_if/logger"
  6. "mtp2_if/models"
  7. "net/http"
  8. "github.com/gin-gonic/gin"
  9. )
  10. // QueryProvincesAndCitiesReq 查询省市信息请求参数
  11. type QueryProvincesAndCitiesReq struct {
  12. ProvinceID int `form:"provinceID"` // 省ID
  13. }
  14. // QueryProvincesAndCitiesRsp 查询省市信息返回模型
  15. type QueryProvincesAndCitiesRsp struct {
  16. Province models.Division // 省
  17. Cities []models.Division // 市
  18. }
  19. // QueryProvincesAndCities 查询省市信息(不包括区)
  20. // @Summary 查询省市信息(不包括区)
  21. // @Produce json
  22. // @Param provinceID query int false "省ID"
  23. // @Success 200 {object} QueryProvincesAndCitiesRsp
  24. // @Failure 500 {object} app.Response
  25. // @Router /Common/QueryProvincesAndCities [get]
  26. // @Tags 通用服务
  27. func QueryProvincesAndCities(c *gin.Context) {
  28. appG := app.Gin{C: c}
  29. // 获取请求参数
  30. var req QueryProvincesAndCitiesReq
  31. if err := appG.C.ShouldBindQuery(&req); err != nil {
  32. logger.GetLogger().Errorf("QueryProvincesAndCities failed: %s", err.Error())
  33. appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
  34. return
  35. }
  36. // 获取省市信息
  37. provinces, err := models.GetProvincesAndCities(req.ProvinceID)
  38. if err != nil {
  39. // 查询失败
  40. logger.GetLogger().Errorf("QueryProvincesAndCities failed: %s", err.Error())
  41. appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  42. return
  43. }
  44. // 分解省市数据
  45. // Golang Map元素取址问题: cannot assign to struct field XXXX in map
  46. // https://blog.csdn.net/makenothing/article/details/105037977
  47. pMap := make(map[string]*QueryProvincesAndCitiesRsp)
  48. // 构建省节点
  49. for _, v := range provinces {
  50. if v.Divisionlevel == "province" {
  51. pMap[v.Divisioncode] = &QueryProvincesAndCitiesRsp{Province: v, Cities: make([]models.Division, 0)}
  52. }
  53. }
  54. // 为省节点增加市信息
  55. for _, v := range provinces {
  56. if v.Divisionlevel == "city" {
  57. pMap[v.Parentcode].Cities = append(pMap[v.Parentcode].Cities, v)
  58. }
  59. }
  60. // map to slice
  61. rst := make([]QueryProvincesAndCitiesRsp, 0)
  62. for _, v := range pMap {
  63. rst = append(rst, *v)
  64. }
  65. // 查询成功
  66. logger.GetLogger().Debugln("QueryProvincesAndCities successed: %v", rst)
  67. appG.Response(http.StatusOK, e.SUCCESS, rst)
  68. }