package common import ( "mtp2_if/global/app" "mtp2_if/global/e" "mtp2_if/logger" "mtp2_if/models" "net/http" "github.com/gin-gonic/gin" ) // QueryProvincesAndCitiesReq 查询省市信息请求参数 type QueryProvincesAndCitiesReq struct { ProvinceID int `form:"provinceID"` // 省ID } // QueryProvincesAndCitiesRsp 查询省市信息返回模型 type QueryProvincesAndCitiesRsp struct { Province models.Division // 省 Cities []models.Division // 市 } // QueryProvincesAndCities 查询省市信息(不包括区) // @Summary 查询省市信息(不包括区) // @Produce json // @Param provinceID query int false "省ID" // @Success 200 {object} QueryProvincesAndCitiesRsp // @Failure 500 {object} app.Response // @Router /Common/QueryProvincesAndCities [get] // @Tags 通用服务 func QueryProvincesAndCities(c *gin.Context) { appG := app.Gin{C: c} // 获取请求参数 var req QueryProvincesAndCitiesReq if err := appG.C.ShouldBindQuery(&req); err != nil { logger.GetLogger().Errorf("QueryProvincesAndCities failed: %s", err.Error()) appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil) return } // 获取省市信息 provinces, err := models.GetProvincesAndCities(req.ProvinceID) if err != nil { // 查询失败 logger.GetLogger().Errorf("QueryProvincesAndCities failed: %s", err.Error()) appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil) return } // 分解省市数据 // Golang Map元素取址问题: cannot assign to struct field XXXX in map // https://blog.csdn.net/makenothing/article/details/105037977 pMap := make(map[string]*QueryProvincesAndCitiesRsp) // 构建省节点 for _, v := range provinces { if v.Divisionlevel == "province" { pMap[v.Divisioncode] = &QueryProvincesAndCitiesRsp{Province: v, Cities: make([]models.Division, 0)} } } // 为省节点增加市信息 for _, v := range provinces { if v.Divisionlevel == "city" { pMap[v.Parentcode].Cities = append(pMap[v.Parentcode].Cities, v) } } // map to slice rst := make([]QueryProvincesAndCitiesRsp, 0) for _, v := range pMap { rst = append(rst, *v) } // 查询成功 logger.GetLogger().Debugln("QueryProvincesAndCities successed: %v", rst) appG.Response(http.StatusOK, e.SUCCESS, rst) }